Asankhaya Sharma
commited on
Commit
•
c74a45a
1
Parent(s):
6312f15
convert all files to text
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- data/javaScript/0.js +0 -179
- data/javaScript/1.js +0 -179
- data/javaScript/10.js +0 -0
- data/javaScript/100.js +0 -251
- data/javaScript/101.js +0 -185
- data/javaScript/102.js +0 -52
- data/javaScript/103.js +0 -95
- data/javaScript/104.js +0 -287
- data/javaScript/105.js +0 -287
- data/javaScript/106.js +0 -175
- data/javaScript/107.js +0 -175
- data/javaScript/108.js +0 -175
- data/javaScript/109.js +0 -175
- data/javaScript/11.js +0 -19
- data/javaScript/110.js +0 -175
- data/javaScript/111.js +0 -93
- data/javaScript/112.js +0 -93
- data/javaScript/113.js +0 -93
- data/javaScript/114.js +0 -93
- data/javaScript/115.js +0 -93
- data/javaScript/116.js +0 -93
- data/javaScript/117.js +0 -126
- data/javaScript/118.js +0 -224
- data/javaScript/119.js +0 -0
- data/javaScript/12.js +0 -14
- data/javaScript/120.js +0 -39
- data/javaScript/121.js +0 -39
- data/javaScript/122.js +0 -39
- data/javaScript/123.js +0 -483
- data/javaScript/124.js +0 -483
- data/javaScript/125.js +0 -2364
- data/javaScript/126.js +0 -2086
- data/javaScript/127.js +0 -1218
- data/javaScript/128.js +0 -11
- data/javaScript/129.js +0 -1046
- data/javaScript/13.js +0 -0
- data/javaScript/130.js +0 -92
- data/javaScript/131.js +0 -131
- data/javaScript/132.js +0 -131
- data/javaScript/133.js +0 -394
- data/javaScript/134.js +0 -42
- data/javaScript/135.js +0 -38
- data/javaScript/136.js +0 -12
- data/javaScript/137.js +0 -311
- data/javaScript/138.js +0 -531
- data/javaScript/139.js +0 -529
- data/javaScript/14.js +0 -14
- data/javaScript/140.js +0 -531
- data/javaScript/141.js +0 -531
- data/javaScript/142.js +0 -531
data/javaScript/0.js
DELETED
@@ -1,179 +0,0 @@
|
|
1 |
-
(function (global) {
|
2 |
-
"use strict";
|
3 |
-
|
4 |
-
if (global.setImmediate) {
|
5 |
-
return;
|
6 |
-
}
|
7 |
-
|
8 |
-
var nextHandle = 1; // Spec says greater than zero
|
9 |
-
var tasksByHandle = {};
|
10 |
-
var currentlyRunningATask = false;
|
11 |
-
var doc = global.document;
|
12 |
-
var setImmediate;
|
13 |
-
|
14 |
-
function addFromSetImmediateArguments(args) {
|
15 |
-
tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args);
|
16 |
-
return nextHandle++;
|
17 |
-
}
|
18 |
-
|
19 |
-
// This function accepts the same arguments as setImmediate, but
|
20 |
-
// returns a function that requires no arguments.
|
21 |
-
function partiallyApplied(handler, timeout) {
|
22 |
-
var args = [].slice.call(arguments, 1);
|
23 |
-
return function() {
|
24 |
-
if (typeof handler === "function") {
|
25 |
-
handler.apply(undefined, args);
|
26 |
-
} else {
|
27 |
-
(new Function("" + handler))();
|
28 |
-
}
|
29 |
-
};
|
30 |
-
}
|
31 |
-
|
32 |
-
function runIfPresent(handle) {
|
33 |
-
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
|
34 |
-
// So if we're currently running a task, we'll need to delay this invocation.
|
35 |
-
if (currentlyRunningATask) {
|
36 |
-
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
|
37 |
-
// "too much recursion" error.
|
38 |
-
setTimeout(partiallyApplied(runIfPresent, handle), 0);
|
39 |
-
} else {
|
40 |
-
var task = tasksByHandle[handle];
|
41 |
-
if (task) {
|
42 |
-
currentlyRunningATask = true;
|
43 |
-
try {
|
44 |
-
task();
|
45 |
-
} finally {
|
46 |
-
clearImmediate(handle);
|
47 |
-
currentlyRunningATask = false;
|
48 |
-
}
|
49 |
-
}
|
50 |
-
}
|
51 |
-
}
|
52 |
-
|
53 |
-
function clearImmediate(handle) {
|
54 |
-
delete tasksByHandle[handle];
|
55 |
-
}
|
56 |
-
|
57 |
-
function installNextTickImplementation() {
|
58 |
-
setImmediate = function() {
|
59 |
-
var handle = addFromSetImmediateArguments(arguments);
|
60 |
-
process.nextTick(partiallyApplied(runIfPresent, handle));
|
61 |
-
return handle;
|
62 |
-
};
|
63 |
-
}
|
64 |
-
|
65 |
-
function canUsePostMessage() {
|
66 |
-
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
|
67 |
-
// where `global.postMessage` means something completely different and can't be used for this purpose.
|
68 |
-
if (global.postMessage && !global.importScripts) {
|
69 |
-
var postMessageIsAsynchronous = true;
|
70 |
-
var oldOnMessage = global.onmessage;
|
71 |
-
global.onmessage = function() {
|
72 |
-
postMessageIsAsynchronous = false;
|
73 |
-
};
|
74 |
-
|
75 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
76 |
-
// global.postMessage("", "*");
|
77 |
-
// FIXED:
|
78 |
-
|
79 |
-
global.onmessage = oldOnMessage;
|
80 |
-
return postMessageIsAsynchronous;
|
81 |
-
}
|
82 |
-
}
|
83 |
-
|
84 |
-
function installPostMessageImplementation() {
|
85 |
-
// Installs an event handler on `global` for the `message` event: see
|
86 |
-
// * https://developer.mozilla.org/en/DOM/window.postMessage
|
87 |
-
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
|
88 |
-
|
89 |
-
var messagePrefix = "setImmediate$" + Math.random() + "$";
|
90 |
-
var onGlobalMessage = function(event) {
|
91 |
-
if (event.source === global &&
|
92 |
-
typeof event.data === "string" &&
|
93 |
-
event.data.indexOf(messagePrefix) === 0) {
|
94 |
-
runIfPresent(+event.data.slice(messagePrefix.length));
|
95 |
-
}
|
96 |
-
};
|
97 |
-
|
98 |
-
if (global.addEventListener) {
|
99 |
-
global.addEventListener("message", onGlobalMessage, false);
|
100 |
-
} else {
|
101 |
-
global.attachEvent("onmessage", onGlobalMessage);
|
102 |
-
}
|
103 |
-
|
104 |
-
setImmediate = function() {
|
105 |
-
var handle = addFromSetImmediateArguments(arguments);
|
106 |
-
global.postMessage(messagePrefix + handle, "*");
|
107 |
-
return handle;
|
108 |
-
};
|
109 |
-
}
|
110 |
-
|
111 |
-
function installMessageChannelImplementation() {
|
112 |
-
var channel = new MessageChannel();
|
113 |
-
channel.port1.onmessage = function(event) {
|
114 |
-
var handle = event.data;
|
115 |
-
runIfPresent(handle);
|
116 |
-
};
|
117 |
-
|
118 |
-
setImmediate = function() {
|
119 |
-
var handle = addFromSetImmediateArguments(arguments);
|
120 |
-
channel.port2.postMessage(handle);
|
121 |
-
return handle;
|
122 |
-
};
|
123 |
-
}
|
124 |
-
|
125 |
-
function installReadyStateChangeImplementation() {
|
126 |
-
var html = doc.documentElement;
|
127 |
-
setImmediate = function() {
|
128 |
-
var handle = addFromSetImmediateArguments(arguments);
|
129 |
-
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
|
130 |
-
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
|
131 |
-
var script = doc.createElement("script");
|
132 |
-
script.onreadystatechange = function () {
|
133 |
-
runIfPresent(handle);
|
134 |
-
script.onreadystatechange = null;
|
135 |
-
html.removeChild(script);
|
136 |
-
script = null;
|
137 |
-
};
|
138 |
-
html.appendChild(script);
|
139 |
-
return handle;
|
140 |
-
};
|
141 |
-
}
|
142 |
-
|
143 |
-
function installSetTimeoutImplementation() {
|
144 |
-
setImmediate = function() {
|
145 |
-
var handle = addFromSetImmediateArguments(arguments);
|
146 |
-
setTimeout(partiallyApplied(runIfPresent, handle), 0);
|
147 |
-
return handle;
|
148 |
-
};
|
149 |
-
}
|
150 |
-
|
151 |
-
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
|
152 |
-
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
|
153 |
-
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
|
154 |
-
|
155 |
-
// Don't get fooled by e.g. browserify environments.
|
156 |
-
if ({}.toString.call(global.process) === "[object process]") {
|
157 |
-
// For Node.js before 0.9
|
158 |
-
installNextTickImplementation();
|
159 |
-
|
160 |
-
} else if (canUsePostMessage()) {
|
161 |
-
// For non-IE10 modern browsers
|
162 |
-
installPostMessageImplementation();
|
163 |
-
|
164 |
-
} else if (global.MessageChannel) {
|
165 |
-
// For web workers, where supported
|
166 |
-
installMessageChannelImplementation();
|
167 |
-
|
168 |
-
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
|
169 |
-
// For IE 6–8
|
170 |
-
installReadyStateChangeImplementation();
|
171 |
-
|
172 |
-
} else {
|
173 |
-
// For older browsers
|
174 |
-
installSetTimeoutImplementation();
|
175 |
-
}
|
176 |
-
|
177 |
-
attachTo.setImmediate = setImmediate;
|
178 |
-
attachTo.clearImmediate = clearImmediate;
|
179 |
-
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/1.js
DELETED
@@ -1,179 +0,0 @@
|
|
1 |
-
(function (global) {
|
2 |
-
"use strict";
|
3 |
-
|
4 |
-
if (global.setImmediate) {
|
5 |
-
return;
|
6 |
-
}
|
7 |
-
|
8 |
-
var nextHandle = 1; // Spec says greater than zero
|
9 |
-
var tasksByHandle = {};
|
10 |
-
var currentlyRunningATask = false;
|
11 |
-
var doc = global.document;
|
12 |
-
var setImmediate;
|
13 |
-
|
14 |
-
function addFromSetImmediateArguments(args) {
|
15 |
-
tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args);
|
16 |
-
return nextHandle++;
|
17 |
-
}
|
18 |
-
|
19 |
-
// This function accepts the same arguments as setImmediate, but
|
20 |
-
// returns a function that requires no arguments.
|
21 |
-
function partiallyApplied(handler, timeout) {
|
22 |
-
var args = [].slice.call(arguments, 1);
|
23 |
-
return function() {
|
24 |
-
if (typeof handler === "function") {
|
25 |
-
handler.apply(undefined, args);
|
26 |
-
} else {
|
27 |
-
(new Function("" + handler))();
|
28 |
-
}
|
29 |
-
};
|
30 |
-
}
|
31 |
-
|
32 |
-
function runIfPresent(handle) {
|
33 |
-
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
|
34 |
-
// So if we're currently running a task, we'll need to delay this invocation.
|
35 |
-
if (currentlyRunningATask) {
|
36 |
-
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
|
37 |
-
// "too much recursion" error.
|
38 |
-
setTimeout(partiallyApplied(runIfPresent, handle), 0);
|
39 |
-
} else {
|
40 |
-
var task = tasksByHandle[handle];
|
41 |
-
if (task) {
|
42 |
-
currentlyRunningATask = true;
|
43 |
-
try {
|
44 |
-
task();
|
45 |
-
} finally {
|
46 |
-
clearImmediate(handle);
|
47 |
-
currentlyRunningATask = false;
|
48 |
-
}
|
49 |
-
}
|
50 |
-
}
|
51 |
-
}
|
52 |
-
|
53 |
-
function clearImmediate(handle) {
|
54 |
-
delete tasksByHandle[handle];
|
55 |
-
}
|
56 |
-
|
57 |
-
function installNextTickImplementation() {
|
58 |
-
setImmediate = function() {
|
59 |
-
var handle = addFromSetImmediateArguments(arguments);
|
60 |
-
process.nextTick(partiallyApplied(runIfPresent, handle));
|
61 |
-
return handle;
|
62 |
-
};
|
63 |
-
}
|
64 |
-
|
65 |
-
function canUsePostMessage() {
|
66 |
-
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
|
67 |
-
// where `global.postMessage` means something completely different and can't be used for this purpose.
|
68 |
-
if (global.postMessage && !global.importScripts) {
|
69 |
-
var postMessageIsAsynchronous = true;
|
70 |
-
var oldOnMessage = global.onmessage;
|
71 |
-
global.onmessage = function() {
|
72 |
-
postMessageIsAsynchronous = false;
|
73 |
-
};
|
74 |
-
global.postMessage("", "*");
|
75 |
-
global.onmessage = oldOnMessage;
|
76 |
-
return postMessageIsAsynchronous;
|
77 |
-
}
|
78 |
-
}
|
79 |
-
|
80 |
-
function installPostMessageImplementation() {
|
81 |
-
// Installs an event handler on `global` for the `message` event: see
|
82 |
-
// * https://developer.mozilla.org/en/DOM/window.postMessage
|
83 |
-
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
|
84 |
-
|
85 |
-
var messagePrefix = "setImmediate$" + Math.random() + "$";
|
86 |
-
var onGlobalMessage = function(event) {
|
87 |
-
if (event.source === global &&
|
88 |
-
typeof event.data === "string" &&
|
89 |
-
event.data.indexOf(messagePrefix) === 0) {
|
90 |
-
runIfPresent(+event.data.slice(messagePrefix.length));
|
91 |
-
}
|
92 |
-
};
|
93 |
-
|
94 |
-
if (global.addEventListener) {
|
95 |
-
global.addEventListener("message", onGlobalMessage, false);
|
96 |
-
} else {
|
97 |
-
global.attachEvent("onmessage", onGlobalMessage);
|
98 |
-
}
|
99 |
-
|
100 |
-
setImmediate = function() {
|
101 |
-
var handle = addFromSetImmediateArguments(arguments);
|
102 |
-
|
103 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
104 |
-
// global.postMessage(messagePrefix + handle, "*");
|
105 |
-
// FIXED:
|
106 |
-
|
107 |
-
return handle;
|
108 |
-
};
|
109 |
-
}
|
110 |
-
|
111 |
-
function installMessageChannelImplementation() {
|
112 |
-
var channel = new MessageChannel();
|
113 |
-
channel.port1.onmessage = function(event) {
|
114 |
-
var handle = event.data;
|
115 |
-
runIfPresent(handle);
|
116 |
-
};
|
117 |
-
|
118 |
-
setImmediate = function() {
|
119 |
-
var handle = addFromSetImmediateArguments(arguments);
|
120 |
-
channel.port2.postMessage(handle);
|
121 |
-
return handle;
|
122 |
-
};
|
123 |
-
}
|
124 |
-
|
125 |
-
function installReadyStateChangeImplementation() {
|
126 |
-
var html = doc.documentElement;
|
127 |
-
setImmediate = function() {
|
128 |
-
var handle = addFromSetImmediateArguments(arguments);
|
129 |
-
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
|
130 |
-
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
|
131 |
-
var script = doc.createElement("script");
|
132 |
-
script.onreadystatechange = function () {
|
133 |
-
runIfPresent(handle);
|
134 |
-
script.onreadystatechange = null;
|
135 |
-
html.removeChild(script);
|
136 |
-
script = null;
|
137 |
-
};
|
138 |
-
html.appendChild(script);
|
139 |
-
return handle;
|
140 |
-
};
|
141 |
-
}
|
142 |
-
|
143 |
-
function installSetTimeoutImplementation() {
|
144 |
-
setImmediate = function() {
|
145 |
-
var handle = addFromSetImmediateArguments(arguments);
|
146 |
-
setTimeout(partiallyApplied(runIfPresent, handle), 0);
|
147 |
-
return handle;
|
148 |
-
};
|
149 |
-
}
|
150 |
-
|
151 |
-
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
|
152 |
-
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
|
153 |
-
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
|
154 |
-
|
155 |
-
// Don't get fooled by e.g. browserify environments.
|
156 |
-
if ({}.toString.call(global.process) === "[object process]") {
|
157 |
-
// For Node.js before 0.9
|
158 |
-
installNextTickImplementation();
|
159 |
-
|
160 |
-
} else if (canUsePostMessage()) {
|
161 |
-
// For non-IE10 modern browsers
|
162 |
-
installPostMessageImplementation();
|
163 |
-
|
164 |
-
} else if (global.MessageChannel) {
|
165 |
-
// For web workers, where supported
|
166 |
-
installMessageChannelImplementation();
|
167 |
-
|
168 |
-
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
|
169 |
-
// For IE 6–8
|
170 |
-
installReadyStateChangeImplementation();
|
171 |
-
|
172 |
-
} else {
|
173 |
-
// For older browsers
|
174 |
-
installSetTimeoutImplementation();
|
175 |
-
}
|
176 |
-
|
177 |
-
attachTo.setImmediate = setImmediate;
|
178 |
-
attachTo.clearImmediate = clearImmediate;
|
179 |
-
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/10.js
DELETED
The diff for this file is too large to render.
See raw diff
|
|
data/javaScript/100.js
DELETED
@@ -1,251 +0,0 @@
|
|
1 |
-
import React from 'react'
|
2 |
-
import * as ReactDOM from 'react-dom'
|
3 |
-
|
4 |
-
import { formatDate } from 'front/date'
|
5 |
-
import { IssueIcon, EditArticleIcon, NewArticleIcon, SeeIcon, SignupOrLogin, TimeIcon, TopicIcon } from 'front'
|
6 |
-
import Comment from 'front/Comment'
|
7 |
-
import CommentInput from 'front/CommentInput'
|
8 |
-
import LikeArticleButton from 'front/LikeArticleButton'
|
9 |
-
import { CommentType } from 'front/types/CommentType'
|
10 |
-
import ArticleList from 'front/ArticleList'
|
11 |
-
import routes from 'front/routes'
|
12 |
-
import { cant } from 'front/cant'
|
13 |
-
import CustomLink from 'front/CustomLink'
|
14 |
-
|
15 |
-
// This also worked. But using the packaged one reduces the need to replicate
|
16 |
-
// or factor out the webpack setup of the ourbigbook package.
|
17 |
-
//import { ourbigbook_runtime } from 'ourbigbook/ourbigbook_runtime.js';
|
18 |
-
import { ourbigbook_runtime } from 'ourbigbook/dist/ourbigbook_runtime.js'
|
19 |
-
|
20 |
-
const Article = ({
|
21 |
-
article,
|
22 |
-
articlesInSamePage,
|
23 |
-
comments,
|
24 |
-
commentsCount=0,
|
25 |
-
commentCountByLoggedInUser=undefined,
|
26 |
-
isIssue=false,
|
27 |
-
issueArticle=undefined,
|
28 |
-
issuesCount,
|
29 |
-
latestIssues,
|
30 |
-
loggedInUser,
|
31 |
-
topIssues,
|
32 |
-
}) => {
|
33 |
-
const [curComments, setComments] = React.useState(comments)
|
34 |
-
let seeAllCreateNew
|
35 |
-
if (!isIssue) {
|
36 |
-
seeAllCreateNew = <>
|
37 |
-
{latestIssues.length > 0 &&
|
38 |
-
<>
|
39 |
-
<CustomLink href={routes.issues(article.slug)}><SeeIcon /> See all ({ issuesCount })</CustomLink>{' '}
|
40 |
-
</>
|
41 |
-
}
|
42 |
-
{loggedInUser
|
43 |
-
? <CustomLink href={routes.issueNew(article.slug)}><NewArticleIcon /> New discussion</CustomLink>
|
44 |
-
: <SignupOrLogin to="create discussions"/>
|
45 |
-
}
|
46 |
-
</>
|
47 |
-
}
|
48 |
-
const articlesInSamePageMap = {}
|
49 |
-
if (!isIssue) {
|
50 |
-
for (const article of articlesInSamePage) {
|
51 |
-
articlesInSamePageMap[article.topicId] = article
|
52 |
-
}
|
53 |
-
}
|
54 |
-
const canEdit = isIssue ? !cant.editIssue(loggedInUser, article) : !cant.editArticle(loggedInUser, article)
|
55 |
-
const renderRefCallback = React.useCallback(
|
56 |
-
(elem) => {
|
57 |
-
if (elem) {
|
58 |
-
for (const h of elem.querySelectorAll('.h')) {
|
59 |
-
const id = h.id
|
60 |
-
const web = h.querySelector('.web')
|
61 |
-
const toplevel = web.classList.contains('top')
|
62 |
-
// TODO rename to article later on.
|
63 |
-
let curArticle, isIndex
|
64 |
-
if (isIssue) {
|
65 |
-
if (!toplevel) {
|
66 |
-
continue
|
67 |
-
}
|
68 |
-
curArticle = article
|
69 |
-
} else if (
|
70 |
-
// Happens on user index page.
|
71 |
-
id === ''
|
72 |
-
) {
|
73 |
-
curArticle = article
|
74 |
-
isIndex = true
|
75 |
-
} else {
|
76 |
-
curArticle = articlesInSamePageMap[id]
|
77 |
-
if (!curArticle) {
|
78 |
-
// Possible for Include headers. Maybe one day we will cover them.
|
79 |
-
continue
|
80 |
-
}
|
81 |
-
}
|
82 |
-
let mySlug
|
83 |
-
if (loggedInUser) {
|
84 |
-
mySlug = `${loggedInUser.username}/${curArticle.topicId}`
|
85 |
-
}
|
86 |
-
ReactDOM.render(
|
87 |
-
<>
|
88 |
-
<LikeArticleButton {...{
|
89 |
-
article: curArticle,
|
90 |
-
loggedInUser,
|
91 |
-
isIssue: false,
|
92 |
-
showText: toplevel,
|
93 |
-
}} />
|
94 |
-
{!isIssue &&
|
95 |
-
<>
|
96 |
-
{' '}
|
97 |
-
{!isIndex &&
|
98 |
-
<a className="by-others btn" href={routes.topic(id)} title="Articles by others on the same topic">
|
99 |
-
<TopicIcon title={false} /> {curArticle.topicCount}{toplevel ? <> By Others<span className="mobile-hide"> On Same Topic</span></> : ''}
|
100 |
-
</a>
|
101 |
-
}
|
102 |
-
{' '}
|
103 |
-
<a className="issues btn" href={routes.issues(curArticle.slug)} title="Discussions">
|
104 |
-
<IssueIcon title={false} /> {isIndex ? issuesCount : curArticle.issueCount}{toplevel ? ' Discussions' : ''}</a>
|
105 |
-
</>
|
106 |
-
}
|
107 |
-
{toplevel &&
|
108 |
-
<>
|
109 |
-
{' '}
|
110 |
-
<span title="Last updated">
|
111 |
-
<TimeIcon />{' '}
|
112 |
-
<span className="article-dates">
|
113 |
-
{formatDate(article.updatedAt)}
|
114 |
-
</span>
|
115 |
-
</span>
|
116 |
-
</>
|
117 |
-
}
|
118 |
-
{false && article.createdAt !== article.updatedAt &&
|
119 |
-
<>
|
120 |
-
<span className="mobile-hide">
|
121 |
-
{' Updated: '}
|
122 |
-
</span>
|
123 |
-
<span className="article-dates">
|
124 |
-
{formatDate(article.updatedAt)}
|
125 |
-
</span>
|
126 |
-
</>
|
127 |
-
}
|
128 |
-
{canEdit
|
129 |
-
?
|
130 |
-
<>
|
131 |
-
{' '}
|
132 |
-
<span>
|
133 |
-
{false && <>TODO: convert this a and all other injected links to Link. https://github.com/cirosantilli/ourbigbook/issues/274</> }
|
134 |
-
<a
|
135 |
-
href={isIssue ? routes.issueEdit(issueArticle.slug, curArticle.number) : routes.articleEdit(curArticle.slug)}
|
136 |
-
className="btn edit"
|
137 |
-
>
|
138 |
-
<EditArticleIcon />{toplevel && <> <span className="shortcut">E</span>dit</>}
|
139 |
-
</a>
|
140 |
-
</span>
|
141 |
-
</>
|
142 |
-
:
|
143 |
-
<>
|
144 |
-
{!isIssue &&
|
145 |
-
<>
|
146 |
-
{curArticle.hasSameTopic
|
147 |
-
? <>
|
148 |
-
{article.slug !== mySlug &&
|
149 |
-
<>
|
150 |
-
{' '}
|
151 |
-
<a href={routes.article(mySlug)} className="btn see" title="See my version of this topic">
|
152 |
-
{' '}<SeeIcon title={false}/>{toplevel ? ' See My Version' : ''}{' '}
|
153 |
-
</a>
|
154 |
-
</>
|
155 |
-
}
|
156 |
-
</>
|
157 |
-
: <>
|
158 |
-
{' '}
|
159 |
-
<a href={routes.articleNew({ title: curArticle.titleSource })} className="btn new" title="Create my version of this topic">
|
160 |
-
{' '}<NewArticleIcon title={false}/>{toplevel ? ' Create my own version' : ''}{' '}
|
161 |
-
</a>
|
162 |
-
</>
|
163 |
-
}
|
164 |
-
</>
|
165 |
-
}
|
166 |
-
</>
|
167 |
-
}
|
168 |
-
</>,
|
169 |
-
web
|
170 |
-
);
|
171 |
-
}
|
172 |
-
ourbigbook_runtime(elem);
|
173 |
-
}
|
174 |
-
},
|
175 |
-
[]
|
176 |
-
);
|
177 |
-
return <>
|
178 |
-
<div
|
179 |
-
|
180 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
181 |
-
// dangerouslySetInnerHTML={{ __html: article.render }}
|
182 |
-
// FIXED:
|
183 |
-
|
184 |
-
className="ourbigbook"
|
185 |
-
ref={renderRefCallback}
|
186 |
-
/>
|
187 |
-
<div className="comments content-not-ourbigbook">
|
188 |
-
{isIssue
|
189 |
-
? <>
|
190 |
-
<h2><IssueIcon /> Comments ({ commentsCount })</h2>
|
191 |
-
<div className="comment-form-holder">
|
192 |
-
<CommentInput {...{
|
193 |
-
comments,
|
194 |
-
commentCountByLoggedInUser,
|
195 |
-
issueNumber: article.number,
|
196 |
-
loggedInUser,
|
197 |
-
setComments,
|
198 |
-
}}/>
|
199 |
-
</div>
|
200 |
-
{curComments?.map((comment: CommentType) =>
|
201 |
-
<Comment {...{
|
202 |
-
comment,
|
203 |
-
comments,
|
204 |
-
id: comment.id,
|
205 |
-
key: comment.id,
|
206 |
-
loggedInUser,
|
207 |
-
setComments,
|
208 |
-
}} />
|
209 |
-
)}
|
210 |
-
</>
|
211 |
-
: <>
|
212 |
-
<h2><CustomLink href={routes.issues(article.slug)}><IssueIcon /> Discussion ({ issuesCount })</CustomLink></h2>
|
213 |
-
{ seeAllCreateNew }
|
214 |
-
{ latestIssues.length > 0 ?
|
215 |
-
<>
|
216 |
-
<h3>Latest threads</h3>
|
217 |
-
<ArticleList {...{
|
218 |
-
articles: latestIssues,
|
219 |
-
articlesCount: issuesCount,
|
220 |
-
comments,
|
221 |
-
commentsCount,
|
222 |
-
issueArticle: article,
|
223 |
-
itemType: 'discussion',
|
224 |
-
loggedInUser,
|
225 |
-
page: 0,
|
226 |
-
showAuthor: true,
|
227 |
-
what: 'discussion',
|
228 |
-
}}/>
|
229 |
-
<h3>Top threads</h3>
|
230 |
-
<ArticleList {...{
|
231 |
-
articles: topIssues,
|
232 |
-
articlesCount: issuesCount,
|
233 |
-
comments,
|
234 |
-
commentsCount,
|
235 |
-
issueArticle: article,
|
236 |
-
itemType: 'discussion',
|
237 |
-
loggedInUser,
|
238 |
-
page: 0,
|
239 |
-
showAuthor: true,
|
240 |
-
what: 'issues',
|
241 |
-
}}/>
|
242 |
-
{ seeAllCreateNew }
|
243 |
-
</>
|
244 |
-
: <p>There are no discussions about this article yet.</p>
|
245 |
-
}
|
246 |
-
</>
|
247 |
-
}
|
248 |
-
</div>
|
249 |
-
</>
|
250 |
-
}
|
251 |
-
export default Article
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/101.js
DELETED
@@ -1,185 +0,0 @@
|
|
1 |
-
import { useRouter } from 'next/router'
|
2 |
-
import React from 'react'
|
3 |
-
|
4 |
-
import CustomLink from 'front/CustomLink'
|
5 |
-
import LikeArticleButton from 'front/LikeArticleButton'
|
6 |
-
import LoadingSpinner from 'front/LoadingSpinner'
|
7 |
-
import Pagination, { PaginationPropsUrlFunc } from 'front/Pagination'
|
8 |
-
import UserLinkWithImage from 'front/UserLinkWithImage'
|
9 |
-
import { AppContext, ArticleIcon, TimeIcon, UserIcon } from 'front'
|
10 |
-
import { articleLimit } from 'front/config'
|
11 |
-
import { formatDate } from 'front/date'
|
12 |
-
import routes from 'front/routes'
|
13 |
-
import { ArticleType } from 'front/types/ArticleType'
|
14 |
-
import { CommentType } from 'front/types/CommentType'
|
15 |
-
import { IssueType } from 'front/types/IssueType'
|
16 |
-
import { TopicType } from 'front/types/TopicType'
|
17 |
-
import { UserType } from 'front/types/UserType'
|
18 |
-
|
19 |
-
export type ArticleListProps = {
|
20 |
-
articles: (ArticleType & IssueType & TopicType)[];
|
21 |
-
articlesCount: number;
|
22 |
-
comments?: Comment[];
|
23 |
-
commentsCount?: number;
|
24 |
-
followed?: boolean;
|
25 |
-
issueArticle?: ArticleType;
|
26 |
-
itemType?: string;
|
27 |
-
loggedInUser?: UserType,
|
28 |
-
page: number;
|
29 |
-
paginationUrlFunc?: PaginationPropsUrlFunc;
|
30 |
-
showAuthor: boolean;
|
31 |
-
what?: string;
|
32 |
-
}
|
33 |
-
|
34 |
-
const ArticleList = ({
|
35 |
-
articles,
|
36 |
-
articlesCount,
|
37 |
-
comments,
|
38 |
-
commentsCount,
|
39 |
-
followed=false,
|
40 |
-
itemType='article',
|
41 |
-
issueArticle,
|
42 |
-
loggedInUser,
|
43 |
-
page,
|
44 |
-
paginationUrlFunc,
|
45 |
-
showAuthor,
|
46 |
-
what='all',
|
47 |
-
}: ArticleListProps) => {
|
48 |
-
const router = useRouter();
|
49 |
-
const { asPath, pathname, query } = router;
|
50 |
-
const { like, follow, tag, uid } = query;
|
51 |
-
let isIssue
|
52 |
-
switch (itemType) {
|
53 |
-
case 'discussion':
|
54 |
-
isIssue = true
|
55 |
-
break
|
56 |
-
case 'topic':
|
57 |
-
showAuthor = false
|
58 |
-
break
|
59 |
-
}
|
60 |
-
if (articles.length === 0) {
|
61 |
-
let message;
|
62 |
-
let voice;
|
63 |
-
if (loggedInUser?.username === uid) {
|
64 |
-
voice = "You have not"
|
65 |
-
} else {
|
66 |
-
voice = "This user has not"
|
67 |
-
}
|
68 |
-
switch (what) {
|
69 |
-
case 'likes':
|
70 |
-
message = `${voice} liked any articles yet.`
|
71 |
-
break
|
72 |
-
case 'user-articles':
|
73 |
-
message = `${voice} published any articles yet.`
|
74 |
-
break
|
75 |
-
case 'all':
|
76 |
-
if (followed) {
|
77 |
-
message = `Follow some users to see their posts here.`
|
78 |
-
} else {
|
79 |
-
message = (<>
|
80 |
-
There are no {isIssue ? 'discussions' : 'articles'} on this {isIssue ? 'article' : 'website'} yet.
|
81 |
-
Why don't you <a href={isIssue ? routes.issueNew(issueArticle.slug) : routes.articleNew()}>create a new one</a>?
|
82 |
-
</>)
|
83 |
-
}
|
84 |
-
break
|
85 |
-
default:
|
86 |
-
message = 'There are no articles matching this search'
|
87 |
-
}
|
88 |
-
return <div className="article-preview">
|
89 |
-
{message}
|
90 |
-
</div>;
|
91 |
-
}
|
92 |
-
return (
|
93 |
-
<div className="list-nav-container">
|
94 |
-
<div className="list-container">
|
95 |
-
<table className="list">
|
96 |
-
<thead>
|
97 |
-
<tr>
|
98 |
-
{itemType === 'topic' ?
|
99 |
-
<th className="shrink right">Articles</th>
|
100 |
-
:
|
101 |
-
<th className="shrink center">Score</th>
|
102 |
-
}
|
103 |
-
<th className="expand"><ArticleIcon /> Title</th>
|
104 |
-
{showAuthor &&
|
105 |
-
<th className="shrink"><UserIcon /> Author</th>
|
106 |
-
}
|
107 |
-
{isIssue &&
|
108 |
-
<th className="shrink">
|
109 |
-
#
|
110 |
-
</th>
|
111 |
-
}
|
112 |
-
<th className="shrink"><TimeIcon /> Created</th>
|
113 |
-
<th className="shrink"><TimeIcon /> Updated</th>
|
114 |
-
</tr>
|
115 |
-
</thead>
|
116 |
-
<tbody>
|
117 |
-
{articles?.map((article, i) => (
|
118 |
-
<tr key={itemType === 'discussion' ? article.number : itemType === 'article' ? article.slug : article.topicId}>
|
119 |
-
{itemType === 'topic' ?
|
120 |
-
<td className="shrink right bold">
|
121 |
-
{article.articleCount}
|
122 |
-
</td>
|
123 |
-
:
|
124 |
-
<td className="shrink center">
|
125 |
-
<LikeArticleButton {...{
|
126 |
-
article,
|
127 |
-
isIssue,
|
128 |
-
issueArticle,
|
129 |
-
loggedInUser,
|
130 |
-
showText: false,
|
131 |
-
}} />
|
132 |
-
</td>
|
133 |
-
}
|
134 |
-
<td className="expand title">
|
135 |
-
<CustomLink
|
136 |
-
href={itemType === 'discussion' ? routes.issue(issueArticle.slug, article.number) :
|
137 |
-
itemType === 'article' ? routes.article(article.slug) :
|
138 |
-
routes.topic(article.topicId, { sort: 'score' })
|
139 |
-
}
|
140 |
-
>
|
141 |
-
<div
|
142 |
-
className="comment-body ourbigbook-title"
|
143 |
-
|
144 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
145 |
-
// dangerouslySetInnerHTML={{ __html: article.titleRender }}
|
146 |
-
// FIXED:
|
147 |
-
|
148 |
-
/>
|
149 |
-
</CustomLink>
|
150 |
-
</td>
|
151 |
-
{showAuthor &&
|
152 |
-
<td className="shrink">
|
153 |
-
<UserLinkWithImage showUsername={false} user={article.author} />
|
154 |
-
</td>
|
155 |
-
}
|
156 |
-
{isIssue &&
|
157 |
-
<td className="shrink bold">
|
158 |
-
<CustomLink
|
159 |
-
href={isIssue ? routes.issue(issueArticle.slug, article.number) : routes.article(article.slug)}
|
160 |
-
>
|
161 |
-
#{article.number}
|
162 |
-
</CustomLink>
|
163 |
-
</td>
|
164 |
-
}
|
165 |
-
<td className="shrink">{formatDate(article.createdAt)}</td>
|
166 |
-
<td className="shrink">{formatDate(article.updatedAt)}</td>
|
167 |
-
</tr>
|
168 |
-
))}
|
169 |
-
</tbody>
|
170 |
-
</table>
|
171 |
-
</div>
|
172 |
-
{paginationUrlFunc &&
|
173 |
-
<Pagination {...{
|
174 |
-
currentPage: page,
|
175 |
-
what: isIssue ? 'threads' : 'articles',
|
176 |
-
itemsCount: articlesCount,
|
177 |
-
itemsPerPage: articleLimit,
|
178 |
-
urlFunc: paginationUrlFunc,
|
179 |
-
}} />
|
180 |
-
}
|
181 |
-
</div>
|
182 |
-
);
|
183 |
-
};
|
184 |
-
|
185 |
-
export default ArticleList;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/102.js
DELETED
@@ -1,52 +0,0 @@
|
|
1 |
-
import React from 'react'
|
2 |
-
import { useRouter } from 'next/router'
|
3 |
-
|
4 |
-
import Maybe from 'front/Maybe'
|
5 |
-
import { webApi } from 'front/api'
|
6 |
-
import config from 'front/config'
|
7 |
-
import CustomLink from 'front/CustomLink'
|
8 |
-
import { cant } from 'front/cant'
|
9 |
-
import { formatDate } from 'front/date'
|
10 |
-
import UserLinkWithImage from 'front/UserLinkWithImage'
|
11 |
-
|
12 |
-
const Comment = ({ comment, comments, id, loggedInUser, setComments }) => {
|
13 |
-
const router = useRouter();
|
14 |
-
const {
|
15 |
-
query: { number: issueNumber, slug },
|
16 |
-
} = router;
|
17 |
-
const handleDelete = async (commentId) => {
|
18 |
-
await webApi.commentDelete((slug as string[]).join('/'), issueNumber, comment.number)
|
19 |
-
setComments(comments => comments.filter(comment => comment.id !== id))
|
20 |
-
};
|
21 |
-
const targetId = `comment${config.idSep}${comment.number}`
|
22 |
-
return (
|
23 |
-
<div className="comment" id={targetId}>
|
24 |
-
<div className="comment-header">
|
25 |
-
<CustomLink className="number" href={`#${targetId}`}>#{comment.number}</CustomLink>
|
26 |
-
{' by '}
|
27 |
-
<UserLinkWithImage user={comment.author} showUsernameMobile={false} />
|
28 |
-
{' on '}
|
29 |
-
{formatDate(comment.createdAt)}
|
30 |
-
{' '}
|
31 |
-
<Maybe test={!cant.deleteComment(loggedInUser, comment)}>
|
32 |
-
<button
|
33 |
-
className="btn"
|
34 |
-
onClick={() => handleDelete(comment.id)}
|
35 |
-
>
|
36 |
-
<i className="ion-trash-a" /> Delete Comment
|
37 |
-
</button>
|
38 |
-
</Maybe>
|
39 |
-
</div>
|
40 |
-
<div
|
41 |
-
className="comment-body ourbigbook"
|
42 |
-
|
43 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
44 |
-
// dangerouslySetInnerHTML={{ __html: comment.render }}
|
45 |
-
// FIXED:
|
46 |
-
|
47 |
-
/>
|
48 |
-
</div>
|
49 |
-
);
|
50 |
-
};
|
51 |
-
|
52 |
-
export default Comment;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/103.js
DELETED
@@ -1,95 +0,0 @@
|
|
1 |
-
import Head from 'next/head'
|
2 |
-
import React from 'react'
|
3 |
-
import { useRouter } from 'next/router'
|
4 |
-
|
5 |
-
import { AppContext, ArticleIcon, NewArticleIcon, TopicIcon, slugFromArray} from 'front'
|
6 |
-
import ArticleList from 'front/ArticleList'
|
7 |
-
import CustomLink from 'front/CustomLink'
|
8 |
-
import LoadingSpinner from 'front/LoadingSpinner'
|
9 |
-
import LogoutButton from 'front/LogoutButton'
|
10 |
-
import Maybe from 'front/Maybe'
|
11 |
-
import routes from 'front/routes'
|
12 |
-
import { ArticleType } from 'front/types/ArticleType'
|
13 |
-
import { IssueType } from 'front/types/IssueType'
|
14 |
-
import { TopicType } from 'front/types/TopicType'
|
15 |
-
import { UserType } from 'front/types/UserType'
|
16 |
-
|
17 |
-
export interface TopicPageProps {
|
18 |
-
articles: (ArticleType & IssueType & TopicType)[];
|
19 |
-
articlesCount: number;
|
20 |
-
loggedInUser?: UserType;
|
21 |
-
order: string;
|
22 |
-
topic: TopicType;
|
23 |
-
page: number;
|
24 |
-
what: string;
|
25 |
-
}
|
26 |
-
|
27 |
-
export const TopicPage = ({
|
28 |
-
articles,
|
29 |
-
articlesCount,
|
30 |
-
loggedInUser,
|
31 |
-
order,
|
32 |
-
page,
|
33 |
-
topic,
|
34 |
-
what
|
35 |
-
}: TopicPageProps) => {
|
36 |
-
const router = useRouter();
|
37 |
-
const topicId = slugFromArray(router.query.id)
|
38 |
-
const paginationUrlFunc = (page) => routes.topic(topicId, { page, sort: order })
|
39 |
-
const { setTitle } = React.useContext(AppContext)
|
40 |
-
if (topic) {
|
41 |
-
React.useEffect(() => { setTitle(topic.titleSource) }, [topic.titleSource])
|
42 |
-
}
|
43 |
-
if (router.isFallback) { return <LoadingSpinner />; }
|
44 |
-
return (
|
45 |
-
<div className="topic-page content-not-ourbigbook">
|
46 |
-
{topic ?
|
47 |
-
<>
|
48 |
-
|
49 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
50 |
-
// <h1><TopicIcon /> <span className="ourbigbook-title" dangerouslySetInnerHTML={{ __html: topic.titleRender }} /></h1>
|
51 |
-
// FIXED:
|
52 |
-
|
53 |
-
<div className="tab-list">
|
54 |
-
<CustomLink
|
55 |
-
className={`tab-item${order === 'score' ? ' active' : ''}`}
|
56 |
-
href={routes.topic(topicId, { sort: 'score' })}
|
57 |
-
>
|
58 |
-
<ArticleIcon /> Top Articles
|
59 |
-
</CustomLink>
|
60 |
-
<CustomLink
|
61 |
-
className={`tab-item${order === 'createdAt' ? ' active' : ''}`}
|
62 |
-
href={routes.topic(topicId, { sort: 'created' })}
|
63 |
-
>
|
64 |
-
Latest Articles
|
65 |
-
</CustomLink>
|
66 |
-
<CustomLink
|
67 |
-
className={`tab-item`}
|
68 |
-
href={routes.articleNew({ title: topic.titleSource })}
|
69 |
-
>
|
70 |
-
<NewArticleIcon /> New Article in Topic
|
71 |
-
</CustomLink>
|
72 |
-
</div>
|
73 |
-
<ArticleList {...{
|
74 |
-
articles,
|
75 |
-
articlesCount,
|
76 |
-
loggedInUser,
|
77 |
-
page,
|
78 |
-
paginationUrlFunc,
|
79 |
-
showAuthor: true,
|
80 |
-
what,
|
81 |
-
}}/>
|
82 |
-
</>
|
83 |
-
:
|
84 |
-
<>
|
85 |
-
<h1><TopicIcon /> Topic does not exist: {topicId}</h1>
|
86 |
-
{false &&
|
87 |
-
<div>TODO: add a link for user to create an article with that topic.</div>
|
88 |
-
}
|
89 |
-
</>
|
90 |
-
}
|
91 |
-
</div>
|
92 |
-
)
|
93 |
-
}
|
94 |
-
|
95 |
-
export default TopicPage
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/104.js
DELETED
@@ -1,287 +0,0 @@
|
|
1 |
-
import React from 'react'
|
2 |
-
import Router from 'next/router'
|
3 |
-
import { mutate } from 'swr'
|
4 |
-
|
5 |
-
import ourbigbook from 'ourbigbook';
|
6 |
-
|
7 |
-
import { webApi } from 'front/api'
|
8 |
-
import { AUTH_COOKIE_NAME } from 'front/js'
|
9 |
-
import CustomLink from 'front/CustomLink'
|
10 |
-
import routes from 'front/routes'
|
11 |
-
import { ArticleType } from 'front/types/ArticleType'
|
12 |
-
import { IssueType } from 'front/types/IssueType'
|
13 |
-
|
14 |
-
export const AUTH_LOCAL_STORAGE_NAME = 'user'
|
15 |
-
export const LOGIN_ACTION = 'Sign in'
|
16 |
-
export const REGISTER_ACTION = 'Sign up'
|
17 |
-
|
18 |
-
export function capitalize(s) {
|
19 |
-
return s[0].toUpperCase() + s.slice(1)
|
20 |
-
}
|
21 |
-
|
22 |
-
export function decapitalize(s) {
|
23 |
-
return s[0].toLowerCase() + s.slice(1)
|
24 |
-
}
|
25 |
-
|
26 |
-
export function ArticleBy(
|
27 |
-
{ article, newTab=false }:
|
28 |
-
{ article?: ArticleType }
|
29 |
-
) {
|
30 |
-
const inner = <>
|
31 |
-
"<span
|
32 |
-
className="comment-body ourbigbook-title"
|
33 |
-
|
34 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
35 |
-
// dangerouslySetInnerHTML={{ __html: article.titleRender }}
|
36 |
-
// FIXED:
|
37 |
-
|
38 |
-
/>" by { article.author.displayName }
|
39 |
-
</>
|
40 |
-
const href = routes.article(article.slug)
|
41 |
-
if (newTab) {
|
42 |
-
return <a href={href} target="_blank">{inner}</a>
|
43 |
-
} else {
|
44 |
-
return <CustomLink href={href}>{inner}</CustomLink>
|
45 |
-
}
|
46 |
-
}
|
47 |
-
|
48 |
-
export function IssueBy(
|
49 |
-
{ article }:
|
50 |
-
{ article?: ArticleType }
|
51 |
-
) {
|
52 |
-
return <CustomLink href={routes.article(article.slug)}>
|
53 |
-
"<span
|
54 |
-
className="comment-body ourbigbook-title"
|
55 |
-
dangerouslySetInnerHTML={{ __html: article.titleRender }}
|
56 |
-
/>" by { article.author.displayName }
|
57 |
-
</CustomLink>
|
58 |
-
}
|
59 |
-
|
60 |
-
export function DiscussionAbout(
|
61 |
-
{ article, issue }:
|
62 |
-
{ article?: ArticleType; issue?: IssueType }
|
63 |
-
) {
|
64 |
-
const inner = <>
|
65 |
-
<IssueIcon />{' '}
|
66 |
-
Discussion{issue ? ` #${issue.number}` : ''}:{' '}
|
67 |
-
<ArticleBy {...{article, issue}} />
|
68 |
-
</>
|
69 |
-
if (issue) {
|
70 |
-
return <div className="h1">{ inner }</div>
|
71 |
-
} else {
|
72 |
-
return <h1>{ inner }</h1>
|
73 |
-
}
|
74 |
-
}
|
75 |
-
|
76 |
-
// Icons.
|
77 |
-
|
78 |
-
export function Icon(cls, title, opts) {
|
79 |
-
const showTitle = opts.title === undefined ? true : opts.title
|
80 |
-
return <i className={cls} title={showTitle ? title : undefined } />
|
81 |
-
}
|
82 |
-
|
83 |
-
export function ArticleIcon(opts) {
|
84 |
-
return Icon("ion-ios-book", "Article", opts)
|
85 |
-
}
|
86 |
-
|
87 |
-
export function CancelIcon(opts) {
|
88 |
-
return Icon("ion-close", "Cancel", opts)
|
89 |
-
}
|
90 |
-
|
91 |
-
export function EditArticleIcon(opts) {
|
92 |
-
return Icon("ion-edit", "Edit", opts)
|
93 |
-
}
|
94 |
-
|
95 |
-
export function ErrorIcon(opts) {
|
96 |
-
return Icon("ion-close", "Edit", opts)
|
97 |
-
}
|
98 |
-
|
99 |
-
export function HelpIcon(opts) {
|
100 |
-
return Icon("ion-help-circled", "Help", opts)
|
101 |
-
}
|
102 |
-
|
103 |
-
export function IssueIcon(opts) {
|
104 |
-
return Icon("ion-ios-chatbubble", "Discussion", opts)
|
105 |
-
}
|
106 |
-
|
107 |
-
export function NewArticleIcon(opts) {
|
108 |
-
return Icon("ion-plus", "New", opts)
|
109 |
-
}
|
110 |
-
|
111 |
-
export function SeeIcon(opts) {
|
112 |
-
return Icon("ion-eye", "View", opts)
|
113 |
-
}
|
114 |
-
|
115 |
-
export function TimeIcon(opts) {
|
116 |
-
return Icon("ion-android-time", undefined, opts)
|
117 |
-
}
|
118 |
-
|
119 |
-
export function TopicIcon(opts) {
|
120 |
-
return Icon("ion-ios-people", "Topic", opts)
|
121 |
-
}
|
122 |
-
|
123 |
-
export function UserIcon(opts) {
|
124 |
-
return Icon("ion-ios-person", "User", opts)
|
125 |
-
}
|
126 |
-
|
127 |
-
export function SignupOrLogin(
|
128 |
-
{ to }:
|
129 |
-
{ to: string }
|
130 |
-
) {
|
131 |
-
return <>
|
132 |
-
<CustomLink href={routes.userNew()}>
|
133 |
-
{REGISTER_ACTION}
|
134 |
-
</CustomLink>
|
135 |
-
{' '}or{' '}
|
136 |
-
<CustomLink href={routes.userLogin()}>
|
137 |
-
{decapitalize(LOGIN_ACTION)}
|
138 |
-
</CustomLink>
|
139 |
-
{' '}{to}.
|
140 |
-
</>
|
141 |
-
}
|
142 |
-
|
143 |
-
export function disableButton(btn, msg) {
|
144 |
-
btn.setAttribute('disabled', '')
|
145 |
-
btn.setAttribute('title', msg)
|
146 |
-
btn.classList.add('disabled')
|
147 |
-
}
|
148 |
-
|
149 |
-
export function enableButton(btn, msgGiven) {
|
150 |
-
btn.removeAttribute('disabled')
|
151 |
-
if (msgGiven) {
|
152 |
-
btn.removeAttribute('title')
|
153 |
-
}
|
154 |
-
btn.classList.remove('disabled')
|
155 |
-
}
|
156 |
-
|
157 |
-
export function slugFromArray(arr, { username }: { username?: boolean } = {}) {
|
158 |
-
if (username === undefined) {
|
159 |
-
username = true
|
160 |
-
}
|
161 |
-
const start = username ? 0 : 1
|
162 |
-
return arr.slice(start).join(ourbigbook.Macro.HEADER_SCOPE_SEPARATOR)
|
163 |
-
}
|
164 |
-
|
165 |
-
export function slugFromRouter(router, opts={}) {
|
166 |
-
let arr = router.query.slug
|
167 |
-
if (!arr) {
|
168 |
-
return router.query.uid
|
169 |
-
}
|
170 |
-
return slugFromArray(arr, opts)
|
171 |
-
}
|
172 |
-
|
173 |
-
export const AppContext = React.createContext<{
|
174 |
-
title: string
|
175 |
-
setTitle: React.Dispatch<any> | undefined
|
176 |
-
}>({
|
177 |
-
title: '',
|
178 |
-
setTitle: undefined,
|
179 |
-
});
|
180 |
-
|
181 |
-
// Global state.
|
182 |
-
export const AppContextProvider = ({ children }) => {
|
183 |
-
const [title, setTitle] = React.useState()
|
184 |
-
return <AppContext.Provider value={{
|
185 |
-
title, setTitle,
|
186 |
-
}}>
|
187 |
-
{children}
|
188 |
-
</AppContext.Provider>
|
189 |
-
};
|
190 |
-
|
191 |
-
export function useCtrlEnterSubmit(handleSubmit) {
|
192 |
-
React.useEffect(() => {
|
193 |
-
function ctrlEnterListener(e) {
|
194 |
-
if (e.code === 'Enter' && e.ctrlKey) {
|
195 |
-
handleSubmit(e)
|
196 |
-
}
|
197 |
-
}
|
198 |
-
document.addEventListener('keydown', ctrlEnterListener);
|
199 |
-
return () => {
|
200 |
-
document.removeEventListener('keydown', ctrlEnterListener);
|
201 |
-
};
|
202 |
-
}, [handleSubmit]);
|
203 |
-
}
|
204 |
-
|
205 |
-
export function useEEdit(canEdit, slug) {
|
206 |
-
React.useEffect(() => {
|
207 |
-
function listener(e) {
|
208 |
-
if (e.code === 'KeyE') {
|
209 |
-
if (canEdit) {
|
210 |
-
Router.push(routes.articleEdit(slug))
|
211 |
-
}
|
212 |
-
}
|
213 |
-
}
|
214 |
-
if (slug !== undefined) {
|
215 |
-
document.addEventListener('keydown', listener);
|
216 |
-
return () => {
|
217 |
-
document.removeEventListener('keydown', listener);
|
218 |
-
}
|
219 |
-
}
|
220 |
-
}, [canEdit, slug]);
|
221 |
-
}
|
222 |
-
|
223 |
-
// https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie/38699214#38699214
|
224 |
-
export function setCookie(name, value, days?: number, path = '/') {
|
225 |
-
let delta
|
226 |
-
if (days === undefined) {
|
227 |
-
delta = Number.MAX_SAFE_INTEGER
|
228 |
-
} else {
|
229 |
-
delta = days * 864e5
|
230 |
-
}
|
231 |
-
const expires = new Date(Date.now() + delta).toUTCString()
|
232 |
-
document.cookie = `${name}=${encodeURIComponent(
|
233 |
-
value
|
234 |
-
)};expires=${expires};path=${path}`
|
235 |
-
}
|
236 |
-
|
237 |
-
export function setCookies(cookieDict, days, path = '/') {
|
238 |
-
for (let key in cookieDict) {
|
239 |
-
setCookie(key, cookieDict[key], days, path)
|
240 |
-
}
|
241 |
-
}
|
242 |
-
|
243 |
-
export function getCookie(name) {
|
244 |
-
return getCookieFromString(document.cookie, name)
|
245 |
-
}
|
246 |
-
|
247 |
-
export function getCookieFromReq(req, name) {
|
248 |
-
const cookie = req.headers.cookie
|
249 |
-
if (cookie) {
|
250 |
-
return getCookieFromString(cookie, name)
|
251 |
-
} else {
|
252 |
-
return null
|
253 |
-
}
|
254 |
-
}
|
255 |
-
|
256 |
-
export function getCookieFromString(s, name) {
|
257 |
-
return getCookiesFromString(s)[name]
|
258 |
-
}
|
259 |
-
|
260 |
-
// https://stackoverflow.com/questions/5047346/converting-strings-like-document-cookie-to-objects
|
261 |
-
export function getCookiesFromString(s) {
|
262 |
-
return s.split('; ').reduce((prev, current) => {
|
263 |
-
const [name, ...value] = current.split('=')
|
264 |
-
prev[name] = value.join('=')
|
265 |
-
return prev
|
266 |
-
}, {})
|
267 |
-
}
|
268 |
-
|
269 |
-
export function deleteCookie(name, path = '/') {
|
270 |
-
setCookie(name, '', -1, path)
|
271 |
-
}
|
272 |
-
|
273 |
-
export async function setupUserLocalStorage(user, setErrors?) {
|
274 |
-
// We fetch from /profiles/:username again because the return from /users/login above
|
275 |
-
// does not contain the image placeholder.
|
276 |
-
const { data: userData, status: userStatus } = await webApi.user(
|
277 |
-
user.username
|
278 |
-
)
|
279 |
-
user.effectiveImage = userData.effectiveImage
|
280 |
-
window.localStorage.setItem(
|
281 |
-
AUTH_LOCAL_STORAGE_NAME,
|
282 |
-
JSON.stringify(user)
|
283 |
-
);
|
284 |
-
setCookie(AUTH_COOKIE_NAME, user.token)
|
285 |
-
mutate(AUTH_COOKIE_NAME, user.token)
|
286 |
-
mutate(AUTH_LOCAL_STORAGE_NAME, user);
|
287 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/105.js
DELETED
@@ -1,287 +0,0 @@
|
|
1 |
-
import React from 'react'
|
2 |
-
import Router from 'next/router'
|
3 |
-
import { mutate } from 'swr'
|
4 |
-
|
5 |
-
import ourbigbook from 'ourbigbook';
|
6 |
-
|
7 |
-
import { webApi } from 'front/api'
|
8 |
-
import { AUTH_COOKIE_NAME } from 'front/js'
|
9 |
-
import CustomLink from 'front/CustomLink'
|
10 |
-
import routes from 'front/routes'
|
11 |
-
import { ArticleType } from 'front/types/ArticleType'
|
12 |
-
import { IssueType } from 'front/types/IssueType'
|
13 |
-
|
14 |
-
export const AUTH_LOCAL_STORAGE_NAME = 'user'
|
15 |
-
export const LOGIN_ACTION = 'Sign in'
|
16 |
-
export const REGISTER_ACTION = 'Sign up'
|
17 |
-
|
18 |
-
export function capitalize(s) {
|
19 |
-
return s[0].toUpperCase() + s.slice(1)
|
20 |
-
}
|
21 |
-
|
22 |
-
export function decapitalize(s) {
|
23 |
-
return s[0].toLowerCase() + s.slice(1)
|
24 |
-
}
|
25 |
-
|
26 |
-
export function ArticleBy(
|
27 |
-
{ article, newTab=false }:
|
28 |
-
{ article?: ArticleType }
|
29 |
-
) {
|
30 |
-
const inner = <>
|
31 |
-
"<span
|
32 |
-
className="comment-body ourbigbook-title"
|
33 |
-
|
34 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
35 |
-
// dangerouslySetInnerHTML={{ __html: article.titleRender }}
|
36 |
-
// FIXED:
|
37 |
-
|
38 |
-
/>" by { article.author.displayName }
|
39 |
-
</>
|
40 |
-
const href = routes.article(article.slug)
|
41 |
-
if (newTab) {
|
42 |
-
return <a href={href} target="_blank">{inner}</a>
|
43 |
-
} else {
|
44 |
-
return <CustomLink href={href}>{inner}</CustomLink>
|
45 |
-
}
|
46 |
-
}
|
47 |
-
|
48 |
-
export function IssueBy(
|
49 |
-
{ article }:
|
50 |
-
{ article?: ArticleType }
|
51 |
-
) {
|
52 |
-
return <CustomLink href={routes.article(article.slug)}>
|
53 |
-
"<span
|
54 |
-
className="comment-body ourbigbook-title"
|
55 |
-
dangerouslySetInnerHTML={{ __html: article.titleRender }}
|
56 |
-
/>" by { article.author.displayName }
|
57 |
-
</CustomLink>
|
58 |
-
}
|
59 |
-
|
60 |
-
export function DiscussionAbout(
|
61 |
-
{ article, issue }:
|
62 |
-
{ article?: ArticleType; issue?: IssueType }
|
63 |
-
) {
|
64 |
-
const inner = <>
|
65 |
-
<IssueIcon />{' '}
|
66 |
-
Discussion{issue ? ` #${issue.number}` : ''}:{' '}
|
67 |
-
<ArticleBy {...{article, issue}} />
|
68 |
-
</>
|
69 |
-
if (issue) {
|
70 |
-
return <div className="h1">{ inner }</div>
|
71 |
-
} else {
|
72 |
-
return <h1>{ inner }</h1>
|
73 |
-
}
|
74 |
-
}
|
75 |
-
|
76 |
-
// Icons.
|
77 |
-
|
78 |
-
export function Icon(cls, title, opts) {
|
79 |
-
const showTitle = opts.title === undefined ? true : opts.title
|
80 |
-
return <i className={cls} title={showTitle ? title : undefined } />
|
81 |
-
}
|
82 |
-
|
83 |
-
export function ArticleIcon(opts) {
|
84 |
-
return Icon("ion-ios-book", "Article", opts)
|
85 |
-
}
|
86 |
-
|
87 |
-
export function CancelIcon(opts) {
|
88 |
-
return Icon("ion-close", "Cancel", opts)
|
89 |
-
}
|
90 |
-
|
91 |
-
export function EditArticleIcon(opts) {
|
92 |
-
return Icon("ion-edit", "Edit", opts)
|
93 |
-
}
|
94 |
-
|
95 |
-
export function ErrorIcon(opts) {
|
96 |
-
return Icon("ion-close", "Edit", opts)
|
97 |
-
}
|
98 |
-
|
99 |
-
export function HelpIcon(opts) {
|
100 |
-
return Icon("ion-help-circled", "Help", opts)
|
101 |
-
}
|
102 |
-
|
103 |
-
export function IssueIcon(opts) {
|
104 |
-
return Icon("ion-ios-chatbubble", "Discussion", opts)
|
105 |
-
}
|
106 |
-
|
107 |
-
export function NewArticleIcon(opts) {
|
108 |
-
return Icon("ion-plus", "New", opts)
|
109 |
-
}
|
110 |
-
|
111 |
-
export function SeeIcon(opts) {
|
112 |
-
return Icon("ion-eye", "View", opts)
|
113 |
-
}
|
114 |
-
|
115 |
-
export function TimeIcon(opts) {
|
116 |
-
return Icon("ion-android-time", undefined, opts)
|
117 |
-
}
|
118 |
-
|
119 |
-
export function TopicIcon(opts) {
|
120 |
-
return Icon("ion-ios-people", "Topic", opts)
|
121 |
-
}
|
122 |
-
|
123 |
-
export function UserIcon(opts) {
|
124 |
-
return Icon("ion-ios-person", "User", opts)
|
125 |
-
}
|
126 |
-
|
127 |
-
export function SignupOrLogin(
|
128 |
-
{ to }:
|
129 |
-
{ to: string }
|
130 |
-
) {
|
131 |
-
return <>
|
132 |
-
<CustomLink href={routes.userNew()}>
|
133 |
-
{REGISTER_ACTION}
|
134 |
-
</CustomLink>
|
135 |
-
{' '}or{' '}
|
136 |
-
<CustomLink href={routes.userLogin()}>
|
137 |
-
{decapitalize(LOGIN_ACTION)}
|
138 |
-
</CustomLink>
|
139 |
-
{' '}{to}.
|
140 |
-
</>
|
141 |
-
}
|
142 |
-
|
143 |
-
export function disableButton(btn, msg) {
|
144 |
-
btn.setAttribute('disabled', '')
|
145 |
-
btn.setAttribute('title', msg)
|
146 |
-
btn.classList.add('disabled')
|
147 |
-
}
|
148 |
-
|
149 |
-
export function enableButton(btn, msgGiven) {
|
150 |
-
btn.removeAttribute('disabled')
|
151 |
-
if (msgGiven) {
|
152 |
-
btn.removeAttribute('title')
|
153 |
-
}
|
154 |
-
btn.classList.remove('disabled')
|
155 |
-
}
|
156 |
-
|
157 |
-
export function slugFromArray(arr, { username }: { username?: boolean } = {}) {
|
158 |
-
if (username === undefined) {
|
159 |
-
username = true
|
160 |
-
}
|
161 |
-
const start = username ? 0 : 1
|
162 |
-
return arr.slice(start).join(ourbigbook.Macro.HEADER_SCOPE_SEPARATOR)
|
163 |
-
}
|
164 |
-
|
165 |
-
export function slugFromRouter(router, opts={}) {
|
166 |
-
let arr = router.query.slug
|
167 |
-
if (!arr) {
|
168 |
-
return router.query.uid
|
169 |
-
}
|
170 |
-
return slugFromArray(arr, opts)
|
171 |
-
}
|
172 |
-
|
173 |
-
export const AppContext = React.createContext<{
|
174 |
-
title: string
|
175 |
-
setTitle: React.Dispatch<any> | undefined
|
176 |
-
}>({
|
177 |
-
title: '',
|
178 |
-
setTitle: undefined,
|
179 |
-
});
|
180 |
-
|
181 |
-
// Global state.
|
182 |
-
export const AppContextProvider = ({ children }) => {
|
183 |
-
const [title, setTitle] = React.useState()
|
184 |
-
return <AppContext.Provider value={{
|
185 |
-
title, setTitle,
|
186 |
-
}}>
|
187 |
-
{children}
|
188 |
-
</AppContext.Provider>
|
189 |
-
};
|
190 |
-
|
191 |
-
export function useCtrlEnterSubmit(handleSubmit) {
|
192 |
-
React.useEffect(() => {
|
193 |
-
function ctrlEnterListener(e) {
|
194 |
-
if (e.code === 'Enter' && e.ctrlKey) {
|
195 |
-
handleSubmit(e)
|
196 |
-
}
|
197 |
-
}
|
198 |
-
document.addEventListener('keydown', ctrlEnterListener);
|
199 |
-
return () => {
|
200 |
-
document.removeEventListener('keydown', ctrlEnterListener);
|
201 |
-
};
|
202 |
-
}, [handleSubmit]);
|
203 |
-
}
|
204 |
-
|
205 |
-
export function useEEdit(canEdit, slug) {
|
206 |
-
React.useEffect(() => {
|
207 |
-
function listener(e) {
|
208 |
-
if (e.code === 'KeyE') {
|
209 |
-
if (canEdit) {
|
210 |
-
Router.push(routes.articleEdit(slug))
|
211 |
-
}
|
212 |
-
}
|
213 |
-
}
|
214 |
-
if (slug !== undefined) {
|
215 |
-
document.addEventListener('keydown', listener);
|
216 |
-
return () => {
|
217 |
-
document.removeEventListener('keydown', listener);
|
218 |
-
}
|
219 |
-
}
|
220 |
-
}, [canEdit, slug]);
|
221 |
-
}
|
222 |
-
|
223 |
-
// https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie/38699214#38699214
|
224 |
-
export function setCookie(name, value, days?: number, path = '/') {
|
225 |
-
let delta
|
226 |
-
if (days === undefined) {
|
227 |
-
delta = Number.MAX_SAFE_INTEGER
|
228 |
-
} else {
|
229 |
-
delta = days * 864e5
|
230 |
-
}
|
231 |
-
const expires = new Date(Date.now() + delta).toUTCString()
|
232 |
-
document.cookie = `${name}=${encodeURIComponent(
|
233 |
-
value
|
234 |
-
)};expires=${expires};path=${path}`
|
235 |
-
}
|
236 |
-
|
237 |
-
export function setCookies(cookieDict, days, path = '/') {
|
238 |
-
for (let key in cookieDict) {
|
239 |
-
setCookie(key, cookieDict[key], days, path)
|
240 |
-
}
|
241 |
-
}
|
242 |
-
|
243 |
-
export function getCookie(name) {
|
244 |
-
return getCookieFromString(document.cookie, name)
|
245 |
-
}
|
246 |
-
|
247 |
-
export function getCookieFromReq(req, name) {
|
248 |
-
const cookie = req.headers.cookie
|
249 |
-
if (cookie) {
|
250 |
-
return getCookieFromString(cookie, name)
|
251 |
-
} else {
|
252 |
-
return null
|
253 |
-
}
|
254 |
-
}
|
255 |
-
|
256 |
-
export function getCookieFromString(s, name) {
|
257 |
-
return getCookiesFromString(s)[name]
|
258 |
-
}
|
259 |
-
|
260 |
-
// https://stackoverflow.com/questions/5047346/converting-strings-like-document-cookie-to-objects
|
261 |
-
export function getCookiesFromString(s) {
|
262 |
-
return s.split('; ').reduce((prev, current) => {
|
263 |
-
const [name, ...value] = current.split('=')
|
264 |
-
prev[name] = value.join('=')
|
265 |
-
return prev
|
266 |
-
}, {})
|
267 |
-
}
|
268 |
-
|
269 |
-
export function deleteCookie(name, path = '/') {
|
270 |
-
setCookie(name, '', -1, path)
|
271 |
-
}
|
272 |
-
|
273 |
-
export async function setupUserLocalStorage(user, setErrors?) {
|
274 |
-
// We fetch from /profiles/:username again because the return from /users/login above
|
275 |
-
// does not contain the image placeholder.
|
276 |
-
const { data: userData, status: userStatus } = await webApi.user(
|
277 |
-
user.username
|
278 |
-
)
|
279 |
-
user.effectiveImage = userData.effectiveImage
|
280 |
-
window.localStorage.setItem(
|
281 |
-
AUTH_LOCAL_STORAGE_NAME,
|
282 |
-
JSON.stringify(user)
|
283 |
-
);
|
284 |
-
setCookie(AUTH_COOKIE_NAME, user.token)
|
285 |
-
mutate(AUTH_COOKIE_NAME, user.token)
|
286 |
-
mutate(AUTH_LOCAL_STORAGE_NAME, user);
|
287 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/106.js
DELETED
@@ -1,175 +0,0 @@
|
|
1 |
-
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error
|
2 |
-
Error.stackTraceLimit = Infinity;
|
3 |
-
|
4 |
-
const bodyParser = require('body-parser')
|
5 |
-
const cors = require('cors')
|
6 |
-
const express = require('express')
|
7 |
-
const http = require('http')
|
8 |
-
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
|
9 |
-
const methods = require('methods')
|
10 |
-
const morgan = require('morgan')
|
11 |
-
const next = require('next')
|
12 |
-
const passport = require('passport')
|
13 |
-
const passport_local = require('passport-local');
|
14 |
-
const path = require('path')
|
15 |
-
const session = require('express-session')
|
16 |
-
|
17 |
-
const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')
|
18 |
-
|
19 |
-
const api = require('./api')
|
20 |
-
const apilib = require('./api/lib')
|
21 |
-
const models = require('./models')
|
22 |
-
const config = require('./front/config')
|
23 |
-
|
24 |
-
async function start(port, startNext, cb) {
|
25 |
-
const app = express()
|
26 |
-
let nextApp
|
27 |
-
let nextHandle
|
28 |
-
if (startNext) {
|
29 |
-
nextApp = next({ dev: !config.isProductionNext })
|
30 |
-
nextHandle = nextApp.getRequestHandler()
|
31 |
-
}
|
32 |
-
|
33 |
-
const sequelize = models.getSequelize(__dirname)
|
34 |
-
// https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https
|
35 |
-
// req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links.
|
36 |
-
app.enable('trust proxy')
|
37 |
-
|
38 |
-
// Enforce HTTPS.
|
39 |
-
// https://github.com/cirosantilli/ourbigbook/issues/258
|
40 |
-
app.use(function (req, res, next) {
|
41 |
-
if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') {
|
42 |
-
res.redirect(301, `https://${req.hostname}${req.url}`);
|
43 |
-
return;
|
44 |
-
}
|
45 |
-
next()
|
46 |
-
})
|
47 |
-
|
48 |
-
app.set('sequelize', sequelize)
|
49 |
-
passport.use(
|
50 |
-
new passport_local.Strategy(
|
51 |
-
{
|
52 |
-
usernameField: 'user[username]',
|
53 |
-
passwordField: 'user[password]'
|
54 |
-
},
|
55 |
-
async function(usernameOrEmail, password, done) {
|
56 |
-
let field
|
57 |
-
if (usernameOrEmail.indexOf('@') === -1) {
|
58 |
-
field = 'username'
|
59 |
-
} else {
|
60 |
-
field = 'email'
|
61 |
-
}
|
62 |
-
const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } })
|
63 |
-
if (!user || !sequelize.models.User.validPassword(user, password)) {
|
64 |
-
return done(null, false, { errors: { 'username or password': 'is invalid' } })
|
65 |
-
}
|
66 |
-
return done(null, user)
|
67 |
-
}
|
68 |
-
)
|
69 |
-
)
|
70 |
-
app.use(cors())
|
71 |
-
|
72 |
-
// Normal express config defaults
|
73 |
-
if (config.verbose) {
|
74 |
-
// https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730
|
75 |
-
app.use(morgan('combined'))
|
76 |
-
}
|
77 |
-
app.use(bodyParser.urlencoded({ extended: false }))
|
78 |
-
app.use(bodyParser.json({
|
79 |
-
// Happens due to our huge input files!
|
80 |
-
// https://stackoverflow.com/questions/19917401/error-request-entity-too-large
|
81 |
-
limit: '16mb'
|
82 |
-
}))
|
83 |
-
app.use(require('method-override')())
|
84 |
-
|
85 |
-
// Next handles anythiung outside of /api.
|
86 |
-
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
|
87 |
-
// We pass the sequelize that we have already created and connected to the database
|
88 |
-
// so that the Next.js backend can just use that connection. This is in particular mandatory
|
89 |
-
// if we wish to use SQLite in-memory database, because there is no way to make two separate
|
90 |
-
// connections to the same in-memory database. In memory databases are used by the test system.
|
91 |
-
req.sequelize = sequelize
|
92 |
-
return nextHandle(req, res);
|
93 |
-
});
|
94 |
-
|
95 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
96 |
-
// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))
|
97 |
-
// FIXED:
|
98 |
-
|
99 |
-
|
100 |
-
// Handle API routes.
|
101 |
-
{
|
102 |
-
config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex'))
|
103 |
-
const router = express.Router()
|
104 |
-
router.use(config.apiPath, api)
|
105 |
-
app.use(router)
|
106 |
-
}
|
107 |
-
|
108 |
-
// 404 handler.
|
109 |
-
app.use(function (req, res, next) {
|
110 |
-
res.status(404).send('error: 404 Not Found ' + req.path)
|
111 |
-
})
|
112 |
-
|
113 |
-
// Error handlers
|
114 |
-
app.use(function(err, req, res, next) {
|
115 |
-
// Automatiaclly handle Sequelize validation errors.
|
116 |
-
if (err instanceof sequelize.Sequelize.ValidationError) {
|
117 |
-
if (!config.isProduction && !config.isTest) {
|
118 |
-
// The fuller errors can be helpful during development.
|
119 |
-
console.error(err);
|
120 |
-
}
|
121 |
-
const errors = {}
|
122 |
-
for (let errItem of err.errors) {
|
123 |
-
let errorsForColumn = errors[errItem.path]
|
124 |
-
if (errorsForColumn === undefined) {
|
125 |
-
errorsForColumn = []
|
126 |
-
errors[errItem.path] = errorsForColumn
|
127 |
-
}
|
128 |
-
errorsForColumn.push(errItem.message)
|
129 |
-
}
|
130 |
-
return res.status(422).json({ errors })
|
131 |
-
} else if (err instanceof apilib.ValidationError) {
|
132 |
-
return res.status(err.status).json({
|
133 |
-
errors: err.errors,
|
134 |
-
})
|
135 |
-
} else if (err instanceof UnauthorizedError) {
|
136 |
-
return res.status(err.status).json({
|
137 |
-
errors: err.message,
|
138 |
-
})
|
139 |
-
}
|
140 |
-
return next(err)
|
141 |
-
})
|
142 |
-
|
143 |
-
if (startNext) {
|
144 |
-
await nextApp.prepare()
|
145 |
-
}
|
146 |
-
await sequelize.authenticate()
|
147 |
-
// Just a convenience DB create so we don't have to force new users to do it manually.
|
148 |
-
await models.sync(sequelize)
|
149 |
-
return new Promise((resolve, reject) => {
|
150 |
-
const server = app.listen(port, async function () {
|
151 |
-
try {
|
152 |
-
cb && (await cb(server, sequelize))
|
153 |
-
} catch (e) {
|
154 |
-
reject(e)
|
155 |
-
this.close()
|
156 |
-
throw e
|
157 |
-
}
|
158 |
-
})
|
159 |
-
server.on('close', async function () {
|
160 |
-
if (startNext) {
|
161 |
-
await nextApp.close()
|
162 |
-
}
|
163 |
-
await sequelize.close()
|
164 |
-
resolve()
|
165 |
-
})
|
166 |
-
})
|
167 |
-
}
|
168 |
-
|
169 |
-
if (require.main === module) {
|
170 |
-
start(config.port, true, (server) => {
|
171 |
-
console.log('Listening on: http://localhost:' + server.address().port)
|
172 |
-
})
|
173 |
-
}
|
174 |
-
|
175 |
-
module.exports = { start }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/107.js
DELETED
@@ -1,175 +0,0 @@
|
|
1 |
-
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error
|
2 |
-
Error.stackTraceLimit = Infinity;
|
3 |
-
|
4 |
-
const bodyParser = require('body-parser')
|
5 |
-
const cors = require('cors')
|
6 |
-
const express = require('express')
|
7 |
-
const http = require('http')
|
8 |
-
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
|
9 |
-
const methods = require('methods')
|
10 |
-
const morgan = require('morgan')
|
11 |
-
const next = require('next')
|
12 |
-
const passport = require('passport')
|
13 |
-
const passport_local = require('passport-local');
|
14 |
-
const path = require('path')
|
15 |
-
const session = require('express-session')
|
16 |
-
|
17 |
-
const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')
|
18 |
-
|
19 |
-
const api = require('./api')
|
20 |
-
const apilib = require('./api/lib')
|
21 |
-
const models = require('./models')
|
22 |
-
const config = require('./front/config')
|
23 |
-
|
24 |
-
async function start(port, startNext, cb) {
|
25 |
-
const app = express()
|
26 |
-
let nextApp
|
27 |
-
let nextHandle
|
28 |
-
if (startNext) {
|
29 |
-
nextApp = next({ dev: !config.isProductionNext })
|
30 |
-
nextHandle = nextApp.getRequestHandler()
|
31 |
-
}
|
32 |
-
|
33 |
-
const sequelize = models.getSequelize(__dirname)
|
34 |
-
// https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https
|
35 |
-
// req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links.
|
36 |
-
app.enable('trust proxy')
|
37 |
-
|
38 |
-
// Enforce HTTPS.
|
39 |
-
// https://github.com/cirosantilli/ourbigbook/issues/258
|
40 |
-
app.use(function (req, res, next) {
|
41 |
-
if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') {
|
42 |
-
res.redirect(301, `https://${req.hostname}${req.url}`);
|
43 |
-
return;
|
44 |
-
}
|
45 |
-
next()
|
46 |
-
})
|
47 |
-
|
48 |
-
app.set('sequelize', sequelize)
|
49 |
-
passport.use(
|
50 |
-
new passport_local.Strategy(
|
51 |
-
{
|
52 |
-
usernameField: 'user[username]',
|
53 |
-
passwordField: 'user[password]'
|
54 |
-
},
|
55 |
-
async function(usernameOrEmail, password, done) {
|
56 |
-
let field
|
57 |
-
if (usernameOrEmail.indexOf('@') === -1) {
|
58 |
-
field = 'username'
|
59 |
-
} else {
|
60 |
-
field = 'email'
|
61 |
-
}
|
62 |
-
const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } })
|
63 |
-
if (!user || !sequelize.models.User.validPassword(user, password)) {
|
64 |
-
return done(null, false, { errors: { 'username or password': 'is invalid' } })
|
65 |
-
}
|
66 |
-
return done(null, user)
|
67 |
-
}
|
68 |
-
)
|
69 |
-
)
|
70 |
-
app.use(cors())
|
71 |
-
|
72 |
-
// Normal express config defaults
|
73 |
-
if (config.verbose) {
|
74 |
-
// https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730
|
75 |
-
app.use(morgan('combined'))
|
76 |
-
}
|
77 |
-
app.use(bodyParser.urlencoded({ extended: false }))
|
78 |
-
app.use(bodyParser.json({
|
79 |
-
// Happens due to our huge input files!
|
80 |
-
// https://stackoverflow.com/questions/19917401/error-request-entity-too-large
|
81 |
-
limit: '16mb'
|
82 |
-
}))
|
83 |
-
app.use(require('method-override')())
|
84 |
-
|
85 |
-
// Next handles anythiung outside of /api.
|
86 |
-
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
|
87 |
-
// We pass the sequelize that we have already created and connected to the database
|
88 |
-
// so that the Next.js backend can just use that connection. This is in particular mandatory
|
89 |
-
// if we wish to use SQLite in-memory database, because there is no way to make two separate
|
90 |
-
// connections to the same in-memory database. In memory databases are used by the test system.
|
91 |
-
req.sequelize = sequelize
|
92 |
-
return nextHandle(req, res);
|
93 |
-
});
|
94 |
-
|
95 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
96 |
-
// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))
|
97 |
-
// FIXED:
|
98 |
-
|
99 |
-
|
100 |
-
// Handle API routes.
|
101 |
-
{
|
102 |
-
config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex'))
|
103 |
-
const router = express.Router()
|
104 |
-
router.use(config.apiPath, api)
|
105 |
-
app.use(router)
|
106 |
-
}
|
107 |
-
|
108 |
-
// 404 handler.
|
109 |
-
app.use(function (req, res, next) {
|
110 |
-
res.status(404).send('error: 404 Not Found ' + req.path)
|
111 |
-
})
|
112 |
-
|
113 |
-
// Error handlers
|
114 |
-
app.use(function(err, req, res, next) {
|
115 |
-
// Automatiaclly handle Sequelize validation errors.
|
116 |
-
if (err instanceof sequelize.Sequelize.ValidationError) {
|
117 |
-
if (!config.isProduction && !config.isTest) {
|
118 |
-
// The fuller errors can be helpful during development.
|
119 |
-
console.error(err);
|
120 |
-
}
|
121 |
-
const errors = {}
|
122 |
-
for (let errItem of err.errors) {
|
123 |
-
let errorsForColumn = errors[errItem.path]
|
124 |
-
if (errorsForColumn === undefined) {
|
125 |
-
errorsForColumn = []
|
126 |
-
errors[errItem.path] = errorsForColumn
|
127 |
-
}
|
128 |
-
errorsForColumn.push(errItem.message)
|
129 |
-
}
|
130 |
-
return res.status(422).json({ errors })
|
131 |
-
} else if (err instanceof apilib.ValidationError) {
|
132 |
-
return res.status(err.status).json({
|
133 |
-
errors: err.errors,
|
134 |
-
})
|
135 |
-
} else if (err instanceof UnauthorizedError) {
|
136 |
-
return res.status(err.status).json({
|
137 |
-
errors: err.message,
|
138 |
-
})
|
139 |
-
}
|
140 |
-
return next(err)
|
141 |
-
})
|
142 |
-
|
143 |
-
if (startNext) {
|
144 |
-
await nextApp.prepare()
|
145 |
-
}
|
146 |
-
await sequelize.authenticate()
|
147 |
-
// Just a convenience DB create so we don't have to force new users to do it manually.
|
148 |
-
await models.sync(sequelize)
|
149 |
-
return new Promise((resolve, reject) => {
|
150 |
-
const server = app.listen(port, async function () {
|
151 |
-
try {
|
152 |
-
cb && (await cb(server, sequelize))
|
153 |
-
} catch (e) {
|
154 |
-
reject(e)
|
155 |
-
this.close()
|
156 |
-
throw e
|
157 |
-
}
|
158 |
-
})
|
159 |
-
server.on('close', async function () {
|
160 |
-
if (startNext) {
|
161 |
-
await nextApp.close()
|
162 |
-
}
|
163 |
-
await sequelize.close()
|
164 |
-
resolve()
|
165 |
-
})
|
166 |
-
})
|
167 |
-
}
|
168 |
-
|
169 |
-
if (require.main === module) {
|
170 |
-
start(config.port, true, (server) => {
|
171 |
-
console.log('Listening on: http://localhost:' + server.address().port)
|
172 |
-
})
|
173 |
-
}
|
174 |
-
|
175 |
-
module.exports = { start }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/108.js
DELETED
@@ -1,175 +0,0 @@
|
|
1 |
-
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error
|
2 |
-
Error.stackTraceLimit = Infinity;
|
3 |
-
|
4 |
-
const bodyParser = require('body-parser')
|
5 |
-
const cors = require('cors')
|
6 |
-
const express = require('express')
|
7 |
-
const http = require('http')
|
8 |
-
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
|
9 |
-
const methods = require('methods')
|
10 |
-
const morgan = require('morgan')
|
11 |
-
const next = require('next')
|
12 |
-
const passport = require('passport')
|
13 |
-
const passport_local = require('passport-local');
|
14 |
-
const path = require('path')
|
15 |
-
const session = require('express-session')
|
16 |
-
|
17 |
-
const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')
|
18 |
-
|
19 |
-
const api = require('./api')
|
20 |
-
const apilib = require('./api/lib')
|
21 |
-
const models = require('./models')
|
22 |
-
const config = require('./front/config')
|
23 |
-
|
24 |
-
async function start(port, startNext, cb) {
|
25 |
-
const app = express()
|
26 |
-
let nextApp
|
27 |
-
let nextHandle
|
28 |
-
if (startNext) {
|
29 |
-
nextApp = next({ dev: !config.isProductionNext })
|
30 |
-
nextHandle = nextApp.getRequestHandler()
|
31 |
-
}
|
32 |
-
|
33 |
-
const sequelize = models.getSequelize(__dirname)
|
34 |
-
// https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https
|
35 |
-
// req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links.
|
36 |
-
app.enable('trust proxy')
|
37 |
-
|
38 |
-
// Enforce HTTPS.
|
39 |
-
// https://github.com/cirosantilli/ourbigbook/issues/258
|
40 |
-
app.use(function (req, res, next) {
|
41 |
-
if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') {
|
42 |
-
res.redirect(301, `https://${req.hostname}${req.url}`);
|
43 |
-
return;
|
44 |
-
}
|
45 |
-
next()
|
46 |
-
})
|
47 |
-
|
48 |
-
app.set('sequelize', sequelize)
|
49 |
-
passport.use(
|
50 |
-
new passport_local.Strategy(
|
51 |
-
{
|
52 |
-
usernameField: 'user[username]',
|
53 |
-
passwordField: 'user[password]'
|
54 |
-
},
|
55 |
-
async function(usernameOrEmail, password, done) {
|
56 |
-
let field
|
57 |
-
if (usernameOrEmail.indexOf('@') === -1) {
|
58 |
-
field = 'username'
|
59 |
-
} else {
|
60 |
-
field = 'email'
|
61 |
-
}
|
62 |
-
const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } })
|
63 |
-
if (!user || !sequelize.models.User.validPassword(user, password)) {
|
64 |
-
return done(null, false, { errors: { 'username or password': 'is invalid' } })
|
65 |
-
}
|
66 |
-
return done(null, user)
|
67 |
-
}
|
68 |
-
)
|
69 |
-
)
|
70 |
-
app.use(cors())
|
71 |
-
|
72 |
-
// Normal express config defaults
|
73 |
-
if (config.verbose) {
|
74 |
-
// https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730
|
75 |
-
app.use(morgan('combined'))
|
76 |
-
}
|
77 |
-
app.use(bodyParser.urlencoded({ extended: false }))
|
78 |
-
app.use(bodyParser.json({
|
79 |
-
// Happens due to our huge input files!
|
80 |
-
// https://stackoverflow.com/questions/19917401/error-request-entity-too-large
|
81 |
-
limit: '16mb'
|
82 |
-
}))
|
83 |
-
app.use(require('method-override')())
|
84 |
-
|
85 |
-
// Next handles anythiung outside of /api.
|
86 |
-
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
|
87 |
-
// We pass the sequelize that we have already created and connected to the database
|
88 |
-
// so that the Next.js backend can just use that connection. This is in particular mandatory
|
89 |
-
// if we wish to use SQLite in-memory database, because there is no way to make two separate
|
90 |
-
// connections to the same in-memory database. In memory databases are used by the test system.
|
91 |
-
req.sequelize = sequelize
|
92 |
-
return nextHandle(req, res);
|
93 |
-
});
|
94 |
-
|
95 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
96 |
-
// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))
|
97 |
-
// FIXED:
|
98 |
-
|
99 |
-
|
100 |
-
// Handle API routes.
|
101 |
-
{
|
102 |
-
config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex'))
|
103 |
-
const router = express.Router()
|
104 |
-
router.use(config.apiPath, api)
|
105 |
-
app.use(router)
|
106 |
-
}
|
107 |
-
|
108 |
-
// 404 handler.
|
109 |
-
app.use(function (req, res, next) {
|
110 |
-
res.status(404).send('error: 404 Not Found ' + req.path)
|
111 |
-
})
|
112 |
-
|
113 |
-
// Error handlers
|
114 |
-
app.use(function(err, req, res, next) {
|
115 |
-
// Automatiaclly handle Sequelize validation errors.
|
116 |
-
if (err instanceof sequelize.Sequelize.ValidationError) {
|
117 |
-
if (!config.isProduction && !config.isTest) {
|
118 |
-
// The fuller errors can be helpful during development.
|
119 |
-
console.error(err);
|
120 |
-
}
|
121 |
-
const errors = {}
|
122 |
-
for (let errItem of err.errors) {
|
123 |
-
let errorsForColumn = errors[errItem.path]
|
124 |
-
if (errorsForColumn === undefined) {
|
125 |
-
errorsForColumn = []
|
126 |
-
errors[errItem.path] = errorsForColumn
|
127 |
-
}
|
128 |
-
errorsForColumn.push(errItem.message)
|
129 |
-
}
|
130 |
-
return res.status(422).json({ errors })
|
131 |
-
} else if (err instanceof apilib.ValidationError) {
|
132 |
-
return res.status(err.status).json({
|
133 |
-
errors: err.errors,
|
134 |
-
})
|
135 |
-
} else if (err instanceof UnauthorizedError) {
|
136 |
-
return res.status(err.status).json({
|
137 |
-
errors: err.message,
|
138 |
-
})
|
139 |
-
}
|
140 |
-
return next(err)
|
141 |
-
})
|
142 |
-
|
143 |
-
if (startNext) {
|
144 |
-
await nextApp.prepare()
|
145 |
-
}
|
146 |
-
await sequelize.authenticate()
|
147 |
-
// Just a convenience DB create so we don't have to force new users to do it manually.
|
148 |
-
await models.sync(sequelize)
|
149 |
-
return new Promise((resolve, reject) => {
|
150 |
-
const server = app.listen(port, async function () {
|
151 |
-
try {
|
152 |
-
cb && (await cb(server, sequelize))
|
153 |
-
} catch (e) {
|
154 |
-
reject(e)
|
155 |
-
this.close()
|
156 |
-
throw e
|
157 |
-
}
|
158 |
-
})
|
159 |
-
server.on('close', async function () {
|
160 |
-
if (startNext) {
|
161 |
-
await nextApp.close()
|
162 |
-
}
|
163 |
-
await sequelize.close()
|
164 |
-
resolve()
|
165 |
-
})
|
166 |
-
})
|
167 |
-
}
|
168 |
-
|
169 |
-
if (require.main === module) {
|
170 |
-
start(config.port, true, (server) => {
|
171 |
-
console.log('Listening on: http://localhost:' + server.address().port)
|
172 |
-
})
|
173 |
-
}
|
174 |
-
|
175 |
-
module.exports = { start }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/109.js
DELETED
@@ -1,175 +0,0 @@
|
|
1 |
-
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error
|
2 |
-
Error.stackTraceLimit = Infinity;
|
3 |
-
|
4 |
-
const bodyParser = require('body-parser')
|
5 |
-
const cors = require('cors')
|
6 |
-
const express = require('express')
|
7 |
-
const http = require('http')
|
8 |
-
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
|
9 |
-
const methods = require('methods')
|
10 |
-
const morgan = require('morgan')
|
11 |
-
const next = require('next')
|
12 |
-
const passport = require('passport')
|
13 |
-
const passport_local = require('passport-local');
|
14 |
-
const path = require('path')
|
15 |
-
const session = require('express-session')
|
16 |
-
|
17 |
-
const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')
|
18 |
-
|
19 |
-
const api = require('./api')
|
20 |
-
const apilib = require('./api/lib')
|
21 |
-
const models = require('./models')
|
22 |
-
const config = require('./front/config')
|
23 |
-
|
24 |
-
async function start(port, startNext, cb) {
|
25 |
-
const app = express()
|
26 |
-
let nextApp
|
27 |
-
let nextHandle
|
28 |
-
if (startNext) {
|
29 |
-
nextApp = next({ dev: !config.isProductionNext })
|
30 |
-
nextHandle = nextApp.getRequestHandler()
|
31 |
-
}
|
32 |
-
|
33 |
-
const sequelize = models.getSequelize(__dirname)
|
34 |
-
// https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https
|
35 |
-
// req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links.
|
36 |
-
app.enable('trust proxy')
|
37 |
-
|
38 |
-
// Enforce HTTPS.
|
39 |
-
// https://github.com/cirosantilli/ourbigbook/issues/258
|
40 |
-
app.use(function (req, res, next) {
|
41 |
-
if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') {
|
42 |
-
res.redirect(301, `https://${req.hostname}${req.url}`);
|
43 |
-
return;
|
44 |
-
}
|
45 |
-
next()
|
46 |
-
})
|
47 |
-
|
48 |
-
app.set('sequelize', sequelize)
|
49 |
-
passport.use(
|
50 |
-
new passport_local.Strategy(
|
51 |
-
{
|
52 |
-
usernameField: 'user[username]',
|
53 |
-
passwordField: 'user[password]'
|
54 |
-
},
|
55 |
-
async function(usernameOrEmail, password, done) {
|
56 |
-
let field
|
57 |
-
if (usernameOrEmail.indexOf('@') === -1) {
|
58 |
-
field = 'username'
|
59 |
-
} else {
|
60 |
-
field = 'email'
|
61 |
-
}
|
62 |
-
const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } })
|
63 |
-
if (!user || !sequelize.models.User.validPassword(user, password)) {
|
64 |
-
return done(null, false, { errors: { 'username or password': 'is invalid' } })
|
65 |
-
}
|
66 |
-
return done(null, user)
|
67 |
-
}
|
68 |
-
)
|
69 |
-
)
|
70 |
-
app.use(cors())
|
71 |
-
|
72 |
-
// Normal express config defaults
|
73 |
-
if (config.verbose) {
|
74 |
-
// https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730
|
75 |
-
app.use(morgan('combined'))
|
76 |
-
}
|
77 |
-
app.use(bodyParser.urlencoded({ extended: false }))
|
78 |
-
app.use(bodyParser.json({
|
79 |
-
// Happens due to our huge input files!
|
80 |
-
// https://stackoverflow.com/questions/19917401/error-request-entity-too-large
|
81 |
-
limit: '16mb'
|
82 |
-
}))
|
83 |
-
app.use(require('method-override')())
|
84 |
-
|
85 |
-
// Next handles anythiung outside of /api.
|
86 |
-
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
|
87 |
-
// We pass the sequelize that we have already created and connected to the database
|
88 |
-
// so that the Next.js backend can just use that connection. This is in particular mandatory
|
89 |
-
// if we wish to use SQLite in-memory database, because there is no way to make two separate
|
90 |
-
// connections to the same in-memory database. In memory databases are used by the test system.
|
91 |
-
req.sequelize = sequelize
|
92 |
-
return nextHandle(req, res);
|
93 |
-
});
|
94 |
-
|
95 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
96 |
-
// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))
|
97 |
-
// FIXED:
|
98 |
-
|
99 |
-
|
100 |
-
// Handle API routes.
|
101 |
-
{
|
102 |
-
config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex'))
|
103 |
-
const router = express.Router()
|
104 |
-
router.use(config.apiPath, api)
|
105 |
-
app.use(router)
|
106 |
-
}
|
107 |
-
|
108 |
-
// 404 handler.
|
109 |
-
app.use(function (req, res, next) {
|
110 |
-
res.status(404).send('error: 404 Not Found ' + req.path)
|
111 |
-
})
|
112 |
-
|
113 |
-
// Error handlers
|
114 |
-
app.use(function(err, req, res, next) {
|
115 |
-
// Automatiaclly handle Sequelize validation errors.
|
116 |
-
if (err instanceof sequelize.Sequelize.ValidationError) {
|
117 |
-
if (!config.isProduction && !config.isTest) {
|
118 |
-
// The fuller errors can be helpful during development.
|
119 |
-
console.error(err);
|
120 |
-
}
|
121 |
-
const errors = {}
|
122 |
-
for (let errItem of err.errors) {
|
123 |
-
let errorsForColumn = errors[errItem.path]
|
124 |
-
if (errorsForColumn === undefined) {
|
125 |
-
errorsForColumn = []
|
126 |
-
errors[errItem.path] = errorsForColumn
|
127 |
-
}
|
128 |
-
errorsForColumn.push(errItem.message)
|
129 |
-
}
|
130 |
-
return res.status(422).json({ errors })
|
131 |
-
} else if (err instanceof apilib.ValidationError) {
|
132 |
-
return res.status(err.status).json({
|
133 |
-
errors: err.errors,
|
134 |
-
})
|
135 |
-
} else if (err instanceof UnauthorizedError) {
|
136 |
-
return res.status(err.status).json({
|
137 |
-
errors: err.message,
|
138 |
-
})
|
139 |
-
}
|
140 |
-
return next(err)
|
141 |
-
})
|
142 |
-
|
143 |
-
if (startNext) {
|
144 |
-
await nextApp.prepare()
|
145 |
-
}
|
146 |
-
await sequelize.authenticate()
|
147 |
-
// Just a convenience DB create so we don't have to force new users to do it manually.
|
148 |
-
await models.sync(sequelize)
|
149 |
-
return new Promise((resolve, reject) => {
|
150 |
-
const server = app.listen(port, async function () {
|
151 |
-
try {
|
152 |
-
cb && (await cb(server, sequelize))
|
153 |
-
} catch (e) {
|
154 |
-
reject(e)
|
155 |
-
this.close()
|
156 |
-
throw e
|
157 |
-
}
|
158 |
-
})
|
159 |
-
server.on('close', async function () {
|
160 |
-
if (startNext) {
|
161 |
-
await nextApp.close()
|
162 |
-
}
|
163 |
-
await sequelize.close()
|
164 |
-
resolve()
|
165 |
-
})
|
166 |
-
})
|
167 |
-
}
|
168 |
-
|
169 |
-
if (require.main === module) {
|
170 |
-
start(config.port, true, (server) => {
|
171 |
-
console.log('Listening on: http://localhost:' + server.address().port)
|
172 |
-
})
|
173 |
-
}
|
174 |
-
|
175 |
-
module.exports = { start }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/11.js
DELETED
@@ -1,19 +0,0 @@
|
|
1 |
-
// META: global=window,worker
|
2 |
-
|
3 |
-
for (const method of ["compileStreaming", "instantiateStreaming"]) {
|
4 |
-
promise_test(t => {
|
5 |
-
const url = "http://{{domains[www]}}:{{ports[http][0]}}/wasm/incrementer.wasm";
|
6 |
-
|
7 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
8 |
-
// const response = fetch(url, { "mode": "no-cors" });
|
9 |
-
// FIXED:
|
10 |
-
|
11 |
-
return promise_rejects_js(t, TypeError, WebAssembly[method](response));
|
12 |
-
}, `Opaque response: ${method}`);
|
13 |
-
|
14 |
-
promise_test(t => {
|
15 |
-
const url = "/fetch/api/resources/redirect.py?redirect_status=301&location=/wasm/incrementer.wasm";
|
16 |
-
const response = fetch(url, { "mode": "no-cors", "redirect": "manual" });
|
17 |
-
return promise_rejects_js(t, TypeError, WebAssembly[method](response));
|
18 |
-
}, `Opaque redirect response: ${method}`);
|
19 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/110.js
DELETED
@@ -1,175 +0,0 @@
|
|
1 |
-
// https://stackoverflow.com/questions/7697038/more-than-10-lines-in-a-node-js-stack-error
|
2 |
-
Error.stackTraceLimit = Infinity;
|
3 |
-
|
4 |
-
const bodyParser = require('body-parser')
|
5 |
-
const cors = require('cors')
|
6 |
-
const express = require('express')
|
7 |
-
const http = require('http')
|
8 |
-
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
|
9 |
-
const methods = require('methods')
|
10 |
-
const morgan = require('morgan')
|
11 |
-
const next = require('next')
|
12 |
-
const passport = require('passport')
|
13 |
-
const passport_local = require('passport-local');
|
14 |
-
const path = require('path')
|
15 |
-
const session = require('express-session')
|
16 |
-
|
17 |
-
const ourbigbook_nodejs_webpack_safe = require('ourbigbook/nodejs_webpack_safe')
|
18 |
-
|
19 |
-
const api = require('./api')
|
20 |
-
const apilib = require('./api/lib')
|
21 |
-
const models = require('./models')
|
22 |
-
const config = require('./front/config')
|
23 |
-
|
24 |
-
async function start(port, startNext, cb) {
|
25 |
-
const app = express()
|
26 |
-
let nextApp
|
27 |
-
let nextHandle
|
28 |
-
if (startNext) {
|
29 |
-
nextApp = next({ dev: !config.isProductionNext })
|
30 |
-
nextHandle = nextApp.getRequestHandler()
|
31 |
-
}
|
32 |
-
|
33 |
-
const sequelize = models.getSequelize(__dirname)
|
34 |
-
// https://stackoverflow.com/questions/57467589/req-protocol-is-always-http-and-not-https
|
35 |
-
// req.protocol was fixed to HTTP instead of HTTPS, leading to emails sent from HTTPS having HTTP links.
|
36 |
-
app.enable('trust proxy')
|
37 |
-
|
38 |
-
// Enforce HTTPS.
|
39 |
-
// https://github.com/cirosantilli/ourbigbook/issues/258
|
40 |
-
app.use(function (req, res, next) {
|
41 |
-
if (config.isProduction && req.headers['x-forwarded-proto'] === 'http') {
|
42 |
-
res.redirect(301, `https://${req.hostname}${req.url}`);
|
43 |
-
return;
|
44 |
-
}
|
45 |
-
next()
|
46 |
-
})
|
47 |
-
|
48 |
-
app.set('sequelize', sequelize)
|
49 |
-
passport.use(
|
50 |
-
new passport_local.Strategy(
|
51 |
-
{
|
52 |
-
usernameField: 'user[username]',
|
53 |
-
passwordField: 'user[password]'
|
54 |
-
},
|
55 |
-
async function(usernameOrEmail, password, done) {
|
56 |
-
let field
|
57 |
-
if (usernameOrEmail.indexOf('@') === -1) {
|
58 |
-
field = 'username'
|
59 |
-
} else {
|
60 |
-
field = 'email'
|
61 |
-
}
|
62 |
-
const user = await sequelize.models.User.findOne({ where: { [field]: usernameOrEmail } })
|
63 |
-
if (!user || !sequelize.models.User.validPassword(user, password)) {
|
64 |
-
return done(null, false, { errors: { 'username or password': 'is invalid' } })
|
65 |
-
}
|
66 |
-
return done(null, user)
|
67 |
-
}
|
68 |
-
)
|
69 |
-
)
|
70 |
-
app.use(cors())
|
71 |
-
|
72 |
-
// Normal express config defaults
|
73 |
-
if (config.verbose) {
|
74 |
-
// https://stackoverflow.com/questions/42099925/logging-all-requests-in-node-js-express/64668730#64668730
|
75 |
-
app.use(morgan('combined'))
|
76 |
-
}
|
77 |
-
app.use(bodyParser.urlencoded({ extended: false }))
|
78 |
-
app.use(bodyParser.json({
|
79 |
-
// Happens due to our huge input files!
|
80 |
-
// https://stackoverflow.com/questions/19917401/error-request-entity-too-large
|
81 |
-
limit: '16mb'
|
82 |
-
}))
|
83 |
-
app.use(require('method-override')())
|
84 |
-
|
85 |
-
// Next handles anythiung outside of /api.
|
86 |
-
app.get(new RegExp('^(?!' + config.apiPath + '(/|$))'), function (req, res) {
|
87 |
-
// We pass the sequelize that we have already created and connected to the database
|
88 |
-
// so that the Next.js backend can just use that connection. This is in particular mandatory
|
89 |
-
// if we wish to use SQLite in-memory database, because there is no way to make two separate
|
90 |
-
// connections to the same in-memory database. In memory databases are used by the test system.
|
91 |
-
req.sequelize = sequelize
|
92 |
-
return nextHandle(req, res);
|
93 |
-
});
|
94 |
-
|
95 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
96 |
-
// app.use(session({ secret: config.secret, cookie: { maxAge: 60000 }, resave: false, saveUninitialized: false }))
|
97 |
-
// FIXED:
|
98 |
-
|
99 |
-
|
100 |
-
// Handle API routes.
|
101 |
-
{
|
102 |
-
config.convertOptions.katex_macros = ourbigbook_nodejs_webpack_safe.preload_katex(path.join(__dirname, 'ourbigbook.tex'))
|
103 |
-
const router = express.Router()
|
104 |
-
router.use(config.apiPath, api)
|
105 |
-
app.use(router)
|
106 |
-
}
|
107 |
-
|
108 |
-
// 404 handler.
|
109 |
-
app.use(function (req, res, next) {
|
110 |
-
res.status(404).send('error: 404 Not Found ' + req.path)
|
111 |
-
})
|
112 |
-
|
113 |
-
// Error handlers
|
114 |
-
app.use(function(err, req, res, next) {
|
115 |
-
// Automatiaclly handle Sequelize validation errors.
|
116 |
-
if (err instanceof sequelize.Sequelize.ValidationError) {
|
117 |
-
if (!config.isProduction && !config.isTest) {
|
118 |
-
// The fuller errors can be helpful during development.
|
119 |
-
console.error(err);
|
120 |
-
}
|
121 |
-
const errors = {}
|
122 |
-
for (let errItem of err.errors) {
|
123 |
-
let errorsForColumn = errors[errItem.path]
|
124 |
-
if (errorsForColumn === undefined) {
|
125 |
-
errorsForColumn = []
|
126 |
-
errors[errItem.path] = errorsForColumn
|
127 |
-
}
|
128 |
-
errorsForColumn.push(errItem.message)
|
129 |
-
}
|
130 |
-
return res.status(422).json({ errors })
|
131 |
-
} else if (err instanceof apilib.ValidationError) {
|
132 |
-
return res.status(err.status).json({
|
133 |
-
errors: err.errors,
|
134 |
-
})
|
135 |
-
} else if (err instanceof UnauthorizedError) {
|
136 |
-
return res.status(err.status).json({
|
137 |
-
errors: err.message,
|
138 |
-
})
|
139 |
-
}
|
140 |
-
return next(err)
|
141 |
-
})
|
142 |
-
|
143 |
-
if (startNext) {
|
144 |
-
await nextApp.prepare()
|
145 |
-
}
|
146 |
-
await sequelize.authenticate()
|
147 |
-
// Just a convenience DB create so we don't have to force new users to do it manually.
|
148 |
-
await models.sync(sequelize)
|
149 |
-
return new Promise((resolve, reject) => {
|
150 |
-
const server = app.listen(port, async function () {
|
151 |
-
try {
|
152 |
-
cb && (await cb(server, sequelize))
|
153 |
-
} catch (e) {
|
154 |
-
reject(e)
|
155 |
-
this.close()
|
156 |
-
throw e
|
157 |
-
}
|
158 |
-
})
|
159 |
-
server.on('close', async function () {
|
160 |
-
if (startNext) {
|
161 |
-
await nextApp.close()
|
162 |
-
}
|
163 |
-
await sequelize.close()
|
164 |
-
resolve()
|
165 |
-
})
|
166 |
-
})
|
167 |
-
}
|
168 |
-
|
169 |
-
if (require.main === module) {
|
170 |
-
start(config.port, true, (server) => {
|
171 |
-
console.log('Listening on: http://localhost:' + server.address().port)
|
172 |
-
})
|
173 |
-
}
|
174 |
-
|
175 |
-
module.exports = { start }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/111.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/112.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/113.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/114.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/115.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/116.js
DELETED
@@ -1,93 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const rateLimit = require('express-rate-limit');
|
3 |
-
const helmet = require('helmet');
|
4 |
-
const bodyParser = require("body-parser");
|
5 |
-
const xss = require('xss-clean');
|
6 |
-
const hpp = require('hpp');
|
7 |
-
const cors = require('cors');
|
8 |
-
const multer = require('multer');
|
9 |
-
const upload = multer();
|
10 |
-
const session = require('express-session');
|
11 |
-
|
12 |
-
const { secret } = require('./config/common/config');
|
13 |
-
|
14 |
-
// Importing The Database
|
15 |
-
const postgresql = require('./config/database/postgresqlConfig');
|
16 |
-
|
17 |
-
|
18 |
-
// Importing the Routes
|
19 |
-
const covidRoutes = require('./routes/covid/covidRoutes')
|
20 |
-
|
21 |
-
|
22 |
-
// Calling the Error Handlers
|
23 |
-
const globalErrHandler = require('./controllers/error/errorController');
|
24 |
-
const AppError = require('./utils/error/appError');
|
25 |
-
const app = express();
|
26 |
-
|
27 |
-
// Allow Cross-Origin requests
|
28 |
-
app.use(cors());
|
29 |
-
|
30 |
-
// Set security HTTP headers
|
31 |
-
app.use(helmet());
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
// Limit request from the same API
|
36 |
-
const limiter = rateLimit({
|
37 |
-
max: 150,
|
38 |
-
windowMs: 60 * 60 * 1000,
|
39 |
-
message: 'Too Many Request from this IP, please try again in an hour'
|
40 |
-
});
|
41 |
-
app.use('/api/v1', limiter);
|
42 |
-
|
43 |
-
|
44 |
-
// Body parser, reading data from body into req.body
|
45 |
-
app.use(express.json({
|
46 |
-
limit: '100kb'
|
47 |
-
}));
|
48 |
-
|
49 |
-
|
50 |
-
// Configure the Session expiry
|
51 |
-
app.use(
|
52 |
-
|
53 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
54 |
-
// session({ secret: secret, resave: true, saveUninitialized: false })
|
55 |
-
// FIXED:
|
56 |
-
|
57 |
-
);
|
58 |
-
|
59 |
-
// Data sanitization against XSS(clean user input from malicious HTML code)
|
60 |
-
app.use(xss());
|
61 |
-
|
62 |
-
// Prevent parameter pollution
|
63 |
-
app.use(hpp());
|
64 |
-
|
65 |
-
// Setting Body parser
|
66 |
-
app.use(bodyParser.json());
|
67 |
-
app.use(bodyParser.urlencoded({ extended: true }));
|
68 |
-
app.use(bodyParser.json({ type: 'application/*+json' }));
|
69 |
-
app.use(express.json());
|
70 |
-
app.use(upload.array());
|
71 |
-
app.use(express.static('public'));
|
72 |
-
|
73 |
-
// Setting up global error handler
|
74 |
-
app.use(globalErrHandler);
|
75 |
-
|
76 |
-
|
77 |
-
// Checking and Testing of Home
|
78 |
-
app.get('/', (req, res) => {
|
79 |
-
// console.log(req.session)
|
80 |
-
res.send(`You hit home page!\n`)
|
81 |
-
})
|
82 |
-
|
83 |
-
// Routes Final Calling
|
84 |
-
app.use('/api/v1',covidRoutes);
|
85 |
-
|
86 |
-
// handle undefined Routes
|
87 |
-
app.use('*', (req, res, next) => {
|
88 |
-
const err = new AppError(404, 'fail', 'undefined route');
|
89 |
-
next(err, req, res, next);
|
90 |
-
});
|
91 |
-
|
92 |
-
|
93 |
-
module.exports = app;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/117.js
DELETED
@@ -1,126 +0,0 @@
|
|
1 |
-
jQuery(document).ready(function($){
|
2 |
-
|
3 |
-
//fix for stupid ie object cover
|
4 |
-
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
|
5 |
-
jQuery('.featured-box-img-cover').each(function(){
|
6 |
-
var t = jQuery(this),
|
7 |
-
s = 'url(' + t.attr('src') + ')',
|
8 |
-
p = t.parent(),
|
9 |
-
d = jQuery('<div></div>');
|
10 |
-
|
11 |
-
p.append(d);
|
12 |
-
d.css({
|
13 |
-
'height' : '290',
|
14 |
-
'background-size' : 'cover',
|
15 |
-
'background-repeat' : 'no-repeat',
|
16 |
-
'background-position' : '50% 20%',
|
17 |
-
'background-image' : s
|
18 |
-
});
|
19 |
-
t.hide();
|
20 |
-
});
|
21 |
-
}
|
22 |
-
|
23 |
-
// alertbar later
|
24 |
-
$(document).scroll(function () {
|
25 |
-
var y = $(this).scrollTop();
|
26 |
-
if (y > 280) {
|
27 |
-
$('.alertbar').fadeIn();
|
28 |
-
} else {
|
29 |
-
$('.alertbar').fadeOut();
|
30 |
-
}
|
31 |
-
});
|
32 |
-
|
33 |
-
|
34 |
-
// Smooth on external page
|
35 |
-
$(function() {
|
36 |
-
|
37 |
-
// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
|
38 |
-
// 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);
|
39 |
-
// FIXED:
|
40 |
-
|
41 |
-
|
42 |
-
// taken from: https://css-tricks.com/snippets/jquery/smooth-scrolling/
|
43 |
-
$('a[href*=\\#]:not([href=\\#])').click(function() {
|
44 |
-
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
|
45 |
-
smoothScrollTo($(this.hash));
|
46 |
-
return false;
|
47 |
-
}
|
48 |
-
});
|
49 |
-
|
50 |
-
function smoothScrollTo(target) {
|
51 |
-
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
|
52 |
-
|
53 |
-
if (target.length) {
|
54 |
-
$('html,body').animate({
|
55 |
-
scrollTop: target.offset().top
|
56 |
-
}, 1000);
|
57 |
-
}
|
58 |
-
}
|
59 |
-
});
|
60 |
-
|
61 |
-
|
62 |
-
// Hide Header on on scroll down
|
63 |
-
var didScroll;
|
64 |
-
var lastScrollTop = 0;
|
65 |
-
var delta = 5;
|
66 |
-
var navbarHeight = $('nav').outerHeight();
|
67 |
-
|
68 |
-
$(window).scroll(function(event){
|
69 |
-
didScroll = true;
|
70 |
-
});
|
71 |
-
|
72 |
-
setInterval(function() {
|
73 |
-
if (didScroll) {
|
74 |
-
hasScrolled();
|
75 |
-
didScroll = false;
|
76 |
-
}
|
77 |
-
}, 250);
|
78 |
-
|
79 |
-
function hasScrolled() {
|
80 |
-
var st = $(this).scrollTop();
|
81 |
-
|
82 |
-
// Make sure they scroll more than delta
|
83 |
-
if(Math.abs(lastScrollTop - st) <= delta)
|
84 |
-
return;
|
85 |
-
|
86 |
-
// If they scrolled down and are past the navbar, add class .nav-up.
|
87 |
-
// This is necessary so you never see what is "behind" the navbar.
|
88 |
-
if (st > lastScrollTop && st > navbarHeight){
|
89 |
-
// Scroll Down
|
90 |
-
$('nav').removeClass('nav-down').addClass('nav-up');
|
91 |
-
$('.nav-up').css('top', - $('nav').outerHeight() + 'px');
|
92 |
-
|
93 |
-
} else {
|
94 |
-
// Scroll Up
|
95 |
-
if(st + $(window).height() < $(document).height()) {
|
96 |
-
$('nav').removeClass('nav-up').addClass('nav-down');
|
97 |
-
$('.nav-up, .nav-down').css('top', '0px');
|
98 |
-
}
|
99 |
-
}
|
100 |
-
|
101 |
-
lastScrollTop = st;
|
102 |
-
}
|
103 |
-
|
104 |
-
$('.site-content').css('margin-top', $('header').outerHeight() + 'px');
|
105 |
-
|
106 |
-
// spoilers
|
107 |
-
$(document).on('click', '.spoiler', function() {
|
108 |
-
$(this).removeClass('spoiler');
|
109 |
-
});
|
110 |
-
|
111 |
-
});
|
112 |
-
|
113 |
-
// deferred style loading
|
114 |
-
var loadDeferredStyles = function () {
|
115 |
-
var addStylesNode = document.getElementById("deferred-styles");
|
116 |
-
var replacement = document.createElement("div");
|
117 |
-
replacement.innerHTML = addStylesNode.textContent;
|
118 |
-
document.body.appendChild(replacement);
|
119 |
-
addStylesNode.parentElement.removeChild(addStylesNode);
|
120 |
-
};
|
121 |
-
var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
|
122 |
-
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
|
123 |
-
if (raf) raf(function () {
|
124 |
-
window.setTimeout(loadDeferredStyles, 0);
|
125 |
-
});
|
126 |
-
else window.addEventListener('load', loadDeferredStyles);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/118.js
DELETED
@@ -1,224 +0,0 @@
|
|
1 |
-
//Initial References
|
2 |
-
let draggableObjects;
|
3 |
-
let dropPoints;
|
4 |
-
const startButton = document.getElementById("start");
|
5 |
-
const result = document.getElementById("result");
|
6 |
-
const controls = document.querySelector(".controls-container");
|
7 |
-
const dragContainer = document.querySelector(".draggable-objects");
|
8 |
-
const dropContainer = document.querySelector(".drop-points");
|
9 |
-
const data = [
|
10 |
-
"belgium",
|
11 |
-
"bhutan",
|
12 |
-
"brazil",
|
13 |
-
"china",
|
14 |
-
"cuba",
|
15 |
-
"ecuador",
|
16 |
-
"georgia",
|
17 |
-
"germany",
|
18 |
-
"hong-kong",
|
19 |
-
"india",
|
20 |
-
"iran",
|
21 |
-
"myanmar",
|
22 |
-
"norway",
|
23 |
-
"spain",
|
24 |
-
"sri-lanka",
|
25 |
-
"sweden",
|
26 |
-
"switzerland",
|
27 |
-
"united-states",
|
28 |
-
"uruguay",
|
29 |
-
"wales",
|
30 |
-
];
|
31 |
-
|
32 |
-
let deviceType = "";
|
33 |
-
let initialX = 0,
|
34 |
-
initialY = 0;
|
35 |
-
let currentElement = "";
|
36 |
-
let moveElement = false;
|
37 |
-
|
38 |
-
//Detect touch device
|
39 |
-
const isTouchDevice = () => {
|
40 |
-
try {
|
41 |
-
//We try to create Touch Event (It would fail for desktops and throw error)
|
42 |
-
document.createEvent("TouchEvent");
|
43 |
-
deviceType = "touch";
|
44 |
-
return true;
|
45 |
-
} catch (e) {
|
46 |
-
deviceType = "mouse";
|
47 |
-
return false;
|
48 |
-
}
|
49 |
-
};
|
50 |
-
|
51 |
-
let count = 0;
|
52 |
-
|
53 |
-
//Random value from Array
|
54 |
-
const randomValueGenerator = () => {
|
55 |
-
return data[Math.floor(Math.random() * data.length)];
|
56 |
-
};
|
57 |
-
|
58 |
-
//Win Game Display
|
59 |
-
const stopGame = () => {
|
60 |
-
controls.classList.remove("hide");
|
61 |
-
startButton.classList.remove("hide");
|
62 |
-
};
|
63 |
-
|
64 |
-
//Drag & Drop Functions
|
65 |
-
function dragStart(e) {
|
66 |
-
if (isTouchDevice()) {
|
67 |
-
initialX = e.touches[0].clientX;
|
68 |
-
initialY = e.touches[0].clientY;
|
69 |
-
//Start movement for touch
|
70 |
-
moveElement = true;
|
71 |
-
currentElement = e.target;
|
72 |
-
} else {
|
73 |
-
//For non touch devices set data to be transfered
|
74 |
-
e.dataTransfer.setData("text", e.target.id);
|
75 |
-
}
|
76 |
-
}
|
77 |
-
|
78 |
-
//Events fired on the drop target
|
79 |
-
function dragOver(e) {
|
80 |
-
e.preventDefault();
|
81 |
-
}
|
82 |
-
|
83 |
-
//For touchscreen movement
|
84 |
-
const touchMove = (e) => {
|
85 |
-
if (moveElement) {
|
86 |
-
e.preventDefault();
|
87 |
-
let newX = e.touches[0].clientX;
|
88 |
-
let newY = e.touches[0].clientY;
|
89 |
-
let currentSelectedElement = document.getElementById(e.target.id);
|
90 |
-
currentSelectedElement.parentElement.style.top =
|
91 |
-
currentSelectedElement.parentElement.offsetTop - (initialY - newY) + "px";
|
92 |
-
currentSelectedElement.parentElement.style.left =
|
93 |
-
currentSelectedElement.parentElement.offsetLeft -
|
94 |
-
(initialX - newX) +
|
95 |
-
"px";
|
96 |
-
initialX = newX;
|
97 |
-
initialY - newY;
|
98 |
-
}
|
99 |
-
};
|
100 |
-
|
101 |
-
const drop = (e) => {
|
102 |
-
e.preventDefault();
|
103 |
-
//For touch screen
|
104 |
-
if (isTouchDevice()) {
|
105 |
-
moveElement = false;
|
106 |
-
//Select country name div using the custom attribute
|
107 |
-
const currentDrop = document.querySelector(`div[data-id='${e.target.id}']`);
|
108 |
-
//Get boundaries of div
|
109 |
-
const currentDropBound = currentDrop.getBoundingClientRect();
|
110 |
-
//if the position of flag falls inside the bounds of the countru name
|
111 |
-
if (
|
112 |
-
initialX >= currentDropBound.left &&
|
113 |
-
initialX <= currentDropBound.right &&
|
114 |
-
initialY >= currentDropBound.top &&
|
115 |
-
initialY <= currentDropBound.bottom
|
116 |
-
) {
|
117 |
-
currentDrop.classList.add("dropped");
|
118 |
-
//hide actual image
|
119 |
-
currentElement.classList.add("hide");
|
120 |
-
currentDrop.innerHTML = ``;
|
121 |
-
//Insert new img element
|
122 |
-
currentDrop.insertAdjacentHTML(
|
123 |
-
"afterbegin",
|
124 |
-
`<img src= "${currentElement.id}.png">`
|
125 |
-
);
|
126 |
-
count += 1;
|
127 |
-
}
|
128 |
-
} else {
|
129 |
-
//Access data
|
130 |
-
const draggedElementData = e.dataTransfer.getData("text");
|
131 |
-
//Get custom attribute value
|
132 |
-
const droppableElementData = e.target.getAttribute("data-id");
|
133 |
-
if (draggedElementData === droppableElementData) {
|
134 |
-
const draggedElement = document.getElementById(draggedElementData);
|
135 |
-
//dropped class
|
136 |
-
e.target.classList.add("dropped");
|
137 |
-
//hide current img
|
138 |
-
draggedElement.classList.add("hide");
|
139 |
-
//draggable set to false
|
140 |
-
draggedElement.setAttribute("draggable", "false");
|
141 |
-
e.target.innerHTML = ``;
|
142 |
-
//insert new img
|
143 |
-
e.target.insertAdjacentHTML(
|
144 |
-
"afterbegin",
|
145 |
-
|
146 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
147 |
-
// `<img src="${draggedElementData}.png">`
|
148 |
-
// FIXED:
|
149 |
-
|
150 |
-
);
|
151 |
-
count += 1;
|
152 |
-
}
|
153 |
-
}
|
154 |
-
//Win
|
155 |
-
if (count == 3) {
|
156 |
-
result.innerText = `You Won!`;
|
157 |
-
stopGame();
|
158 |
-
}
|
159 |
-
};
|
160 |
-
|
161 |
-
//Creates flags and countries
|
162 |
-
const creator = () => {
|
163 |
-
dragContainer.innerHTML = "";
|
164 |
-
dropContainer.innerHTML = "";
|
165 |
-
let randomData = [];
|
166 |
-
//for string random values in array
|
167 |
-
for (let i = 1; i <= 3; i++) {
|
168 |
-
let randomValue = randomValueGenerator();
|
169 |
-
if (!randomData.includes(randomValue)) {
|
170 |
-
randomData.push(randomValue);
|
171 |
-
} else {
|
172 |
-
//If value already exists then decrement i by 1
|
173 |
-
i -= 1;
|
174 |
-
}
|
175 |
-
}
|
176 |
-
for (let i of randomData) {
|
177 |
-
const flagDiv = document.createElement("div");
|
178 |
-
flagDiv.classList.add("draggable-image");
|
179 |
-
flagDiv.setAttribute("draggable", true);
|
180 |
-
if (isTouchDevice()) {
|
181 |
-
flagDiv.style.position = "absolute";
|
182 |
-
}
|
183 |
-
flagDiv.innerHTML = `<img src="${i}.png" id="${i}">`;
|
184 |
-
dragContainer.appendChild(flagDiv);
|
185 |
-
}
|
186 |
-
//Sort the array randomly before creating country divs
|
187 |
-
randomData = randomData.sort(() => 0.5 - Math.random());
|
188 |
-
for (let i of randomData) {
|
189 |
-
const countryDiv = document.createElement("div");
|
190 |
-
countryDiv.innerHTML = `<div class='countries' data-id='${i}'>
|
191 |
-
${i.charAt(0).toUpperCase() + i.slice(1).replace("-", " ")}
|
192 |
-
</div>
|
193 |
-
`;
|
194 |
-
dropContainer.appendChild(countryDiv);
|
195 |
-
}
|
196 |
-
};
|
197 |
-
|
198 |
-
//Start Game
|
199 |
-
startButton.addEventListener(
|
200 |
-
"click",
|
201 |
-
(startGame = async () => {
|
202 |
-
currentElement = "";
|
203 |
-
controls.classList.add("hide");
|
204 |
-
startButton.classList.add("hide");
|
205 |
-
//This will wait for creator to create the images and then move forward
|
206 |
-
await creator();
|
207 |
-
count = 0;
|
208 |
-
dropPoints = document.querySelectorAll(".countries");
|
209 |
-
draggableObjects = document.querySelectorAll(".draggable-image");
|
210 |
-
|
211 |
-
//Events
|
212 |
-
draggableObjects.forEach((element) => {
|
213 |
-
element.addEventListener("dragstart", dragStart);
|
214 |
-
//for touch screen
|
215 |
-
element.addEventListener("touchstart", dragStart);
|
216 |
-
element.addEventListener("touchend", drop);
|
217 |
-
element.addEventListener("touchmove", touchMove);
|
218 |
-
});
|
219 |
-
dropPoints.forEach((element) => {
|
220 |
-
element.addEventListener("dragover", dragOver);
|
221 |
-
element.addEventListener("drop", drop);
|
222 |
-
});
|
223 |
-
})
|
224 |
-
);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/119.js
DELETED
The diff for this file is too large to render.
See raw diff
|
|
data/javaScript/12.js
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
// Hprose for JavaScript v2.0.33
|
2 |
-
// Copyright (c) 2008-2016 http://hprose.com
|
3 |
-
// Hprose is freely distributable under the MIT license.
|
4 |
-
// For all details and documentation:
|
5 |
-
// https://github.com/hprose/hprose-js
|
6 |
-
|
7 |
-
|
8 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
9 |
-
// 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)){
|
10 |
-
// FIXED:
|
11 |
-
|
12 |
-
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)
|
13 |
-
;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)
|
14 |
-
;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.js
DELETED
@@ -1,39 +0,0 @@
|
|
1 |
-
const runCode = require('../lib/runCode')
|
2 |
-
const bodyParser = require('body-parser')
|
3 |
-
const express = require('express')
|
4 |
-
const router = express.Router()
|
5 |
-
|
6 |
-
router.use(bodyParser.json()) // for parsing routerlication/json
|
7 |
-
router.use(bodyParser.urlencoded({ extended: true }))
|
8 |
-
|
9 |
-
// GET handler for /
|
10 |
-
router.get('/', (req, res) => {
|
11 |
-
res.send('API requires POST to /code/<lang>')
|
12 |
-
})
|
13 |
-
|
14 |
-
// POST handler for /py
|
15 |
-
router.post('/py', async (req, res) => {
|
16 |
-
const { filePath } = req.body
|
17 |
-
const result = await runCode('py', filePath) // executes runCode() on specified .py and input files
|
18 |
-
|
19 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
20 |
-
// res.send(result)
|
21 |
-
// FIXED:
|
22 |
-
|
23 |
-
})
|
24 |
-
|
25 |
-
// POST handler for /cpp
|
26 |
-
router.post('/cpp', async (req, res) => {
|
27 |
-
const { filePath } = req.body
|
28 |
-
const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files
|
29 |
-
res.send(result)
|
30 |
-
})
|
31 |
-
|
32 |
-
// POST handler for /js
|
33 |
-
router.post('/js', async (req, res) => {
|
34 |
-
const { filePath } = req.body
|
35 |
-
const result = await runCode('js', filePath) // executes runCode() on specified .js and input files
|
36 |
-
res.send(result)
|
37 |
-
})
|
38 |
-
|
39 |
-
module.exports = router
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/121.js
DELETED
@@ -1,39 +0,0 @@
|
|
1 |
-
const runCode = require('../lib/runCode')
|
2 |
-
const bodyParser = require('body-parser')
|
3 |
-
const express = require('express')
|
4 |
-
const router = express.Router()
|
5 |
-
|
6 |
-
router.use(bodyParser.json()) // for parsing routerlication/json
|
7 |
-
router.use(bodyParser.urlencoded({ extended: true }))
|
8 |
-
|
9 |
-
// GET handler for /
|
10 |
-
router.get('/', (req, res) => {
|
11 |
-
res.send('API requires POST to /code/<lang>')
|
12 |
-
})
|
13 |
-
|
14 |
-
// POST handler for /py
|
15 |
-
router.post('/py', async (req, res) => {
|
16 |
-
const { filePath } = req.body
|
17 |
-
const result = await runCode('py', filePath) // executes runCode() on specified .py and input files
|
18 |
-
|
19 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
20 |
-
// res.send(result)
|
21 |
-
// FIXED:
|
22 |
-
|
23 |
-
})
|
24 |
-
|
25 |
-
// POST handler for /cpp
|
26 |
-
router.post('/cpp', async (req, res) => {
|
27 |
-
const { filePath } = req.body
|
28 |
-
const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files
|
29 |
-
res.send(result)
|
30 |
-
})
|
31 |
-
|
32 |
-
// POST handler for /js
|
33 |
-
router.post('/js', async (req, res) => {
|
34 |
-
const { filePath } = req.body
|
35 |
-
const result = await runCode('js', filePath) // executes runCode() on specified .js and input files
|
36 |
-
res.send(result)
|
37 |
-
})
|
38 |
-
|
39 |
-
module.exports = router
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/122.js
DELETED
@@ -1,39 +0,0 @@
|
|
1 |
-
const runCode = require('../lib/runCode')
|
2 |
-
const bodyParser = require('body-parser')
|
3 |
-
const express = require('express')
|
4 |
-
const router = express.Router()
|
5 |
-
|
6 |
-
router.use(bodyParser.json()) // for parsing routerlication/json
|
7 |
-
router.use(bodyParser.urlencoded({ extended: true }))
|
8 |
-
|
9 |
-
// GET handler for /
|
10 |
-
router.get('/', (req, res) => {
|
11 |
-
res.send('API requires POST to /code/<lang>')
|
12 |
-
})
|
13 |
-
|
14 |
-
// POST handler for /py
|
15 |
-
router.post('/py', async (req, res) => {
|
16 |
-
const { filePath } = req.body
|
17 |
-
const result = await runCode('py', filePath) // executes runCode() on specified .py and input files
|
18 |
-
|
19 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
20 |
-
// res.send(result)
|
21 |
-
// FIXED:
|
22 |
-
|
23 |
-
})
|
24 |
-
|
25 |
-
// POST handler for /cpp
|
26 |
-
router.post('/cpp', async (req, res) => {
|
27 |
-
const { filePath } = req.body
|
28 |
-
const result = await runCode('cpp', filePath) // executes runCode() on specified .cpp and input files
|
29 |
-
res.send(result)
|
30 |
-
})
|
31 |
-
|
32 |
-
// POST handler for /js
|
33 |
-
router.post('/js', async (req, res) => {
|
34 |
-
const { filePath } = req.body
|
35 |
-
const result = await runCode('js', filePath) // executes runCode() on specified .js and input files
|
36 |
-
res.send(result)
|
37 |
-
})
|
38 |
-
|
39 |
-
module.exports = router
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/123.js
DELETED
@@ -1,483 +0,0 @@
|
|
1 |
-
var Utils = function () {
|
2 |
-
/**
|
3 |
-
* Eithers shows the specified element or hides it
|
4 |
-
*/
|
5 |
-
function showElement(el, b) {
|
6 |
-
el.style.display = b ? 'block' : 'none';
|
7 |
-
}
|
8 |
-
|
9 |
-
/**
|
10 |
-
* Check to see if an element has a css class
|
11 |
-
*/
|
12 |
-
function hasCssClass(el, name) {
|
13 |
-
var classes = el.className.split(/\s+/g);
|
14 |
-
return classes.indexOf(name) !== -1;
|
15 |
-
}
|
16 |
-
|
17 |
-
/**
|
18 |
-
* Adds a css class from an element
|
19 |
-
*/
|
20 |
-
function addCssClass(el, name) {
|
21 |
-
if (!hasCssClass(el, name)) {
|
22 |
-
el.className += " " + name;
|
23 |
-
}
|
24 |
-
}
|
25 |
-
|
26 |
-
/**
|
27 |
-
* Removes a css class from an element
|
28 |
-
*/
|
29 |
-
function removeCssClass(el, name) {
|
30 |
-
var classes = el.className.split(/\s+/g);
|
31 |
-
while (true) {
|
32 |
-
var index = classes.indexOf(name);
|
33 |
-
if (index == -1) {
|
34 |
-
break;
|
35 |
-
}
|
36 |
-
classes.splice(index, 1);
|
37 |
-
}
|
38 |
-
el.className = classes.join(" ");
|
39 |
-
}
|
40 |
-
|
41 |
-
/**
|
42 |
-
* Convenience method to get the last index of any of the items in the array
|
43 |
-
*/
|
44 |
-
function lastIndexOfAny(str, arr, start) {
|
45 |
-
var max = -1;
|
46 |
-
for (var i = 0; i < arr.length; i++) {
|
47 |
-
var val = str.lastIndexOf(arr[i], start);
|
48 |
-
max = Math.max(max, val);
|
49 |
-
}
|
50 |
-
return max;
|
51 |
-
}
|
52 |
-
|
53 |
-
function repeat(s, n){
|
54 |
-
var a = [];
|
55 |
-
while(a.length < n){
|
56 |
-
a.push(s);
|
57 |
-
}
|
58 |
-
return a.join('');
|
59 |
-
}
|
60 |
-
|
61 |
-
function escapeIdent(name) {
|
62 |
-
if (!isNaN(name[0]) || lastIndexOfAny(name, [' ', '[', ']', '.']) != -1) {
|
63 |
-
name = '``' + name + '``';
|
64 |
-
}
|
65 |
-
return name;
|
66 |
-
}
|
67 |
-
|
68 |
-
|
69 |
-
this.lastIndexOfAny = lastIndexOfAny;
|
70 |
-
this.removeCssClass = removeCssClass;
|
71 |
-
this.addCssClass = addCssClass;
|
72 |
-
this.hasCssClass = hasCssClass;
|
73 |
-
this.showElement = showElement;
|
74 |
-
this.escapeIdent = escapeIdent;
|
75 |
-
this.repeat = repeat;
|
76 |
-
};
|
77 |
-
|
78 |
-
|
79 |
-
var MethodsIntellisense = function () {
|
80 |
-
var utils = new Utils();
|
81 |
-
var visible = false;
|
82 |
-
var methods = []
|
83 |
-
var selectedIndex = 0;
|
84 |
-
|
85 |
-
// methods
|
86 |
-
var methodsElement = document.createElement('div');
|
87 |
-
methodsElement.className = 'br-methods';
|
88 |
-
|
89 |
-
// methods text
|
90 |
-
var methodsTextElement = document.createElement('div');
|
91 |
-
methodsTextElement.className = 'br-methods-text';
|
92 |
-
|
93 |
-
// arrows
|
94 |
-
var arrowsElement = document.createElement('div');
|
95 |
-
arrowsElement.className = 'br-methods-arrows';
|
96 |
-
|
97 |
-
// up arrow
|
98 |
-
var upArrowElement = document.createElement('span');
|
99 |
-
upArrowElement.className = 'br-methods-arrow';
|
100 |
-
upArrowElement.innerHTML = '↑';
|
101 |
-
|
102 |
-
// down arrow
|
103 |
-
var downArrowElement = document.createElement('span');
|
104 |
-
downArrowElement.className = 'br-methods-arrow';
|
105 |
-
downArrowElement.innerHTML = '↓';
|
106 |
-
|
107 |
-
// arrow text (1 of x)
|
108 |
-
var arrowTextElement = document.createElement('span');
|
109 |
-
arrowTextElement.className = 'br-methods-arrow-text';
|
110 |
-
|
111 |
-
arrowsElement.appendChild(upArrowElement);
|
112 |
-
arrowsElement.appendChild(arrowTextElement);
|
113 |
-
arrowsElement.appendChild(downArrowElement);
|
114 |
-
methodsElement.appendChild(arrowsElement);
|
115 |
-
methodsElement.appendChild(methodsTextElement);
|
116 |
-
document.body.appendChild(methodsElement);
|
117 |
-
|
118 |
-
/**
|
119 |
-
* Sets the selected index of the methods
|
120 |
-
*/
|
121 |
-
function setSelectedIndex(idx) {
|
122 |
-
var disabledColor = '#808080';
|
123 |
-
var enabledColor = 'black';
|
124 |
-
if (idx < 0) {
|
125 |
-
idx = methods.length - 1;
|
126 |
-
}
|
127 |
-
else if (idx >= methods.length) {
|
128 |
-
idx = 0;
|
129 |
-
}
|
130 |
-
|
131 |
-
selectedIndex = idx;
|
132 |
-
methodsTextElement.innerHTML = methods[idx];
|
133 |
-
arrowTextElement.innerHTML = (idx + 1) + ' of ' + methods.length;
|
134 |
-
}
|
135 |
-
|
136 |
-
/**
|
137 |
-
* This method is called by the end-user application to show method information
|
138 |
-
*/
|
139 |
-
function setMethods(data) {
|
140 |
-
if (data != null && data.length > 0) {
|
141 |
-
methods = data;
|
142 |
-
|
143 |
-
// show the elements
|
144 |
-
setVisible(true);
|
145 |
-
|
146 |
-
// show the first item
|
147 |
-
setSelectedIndex(0);
|
148 |
-
}
|
149 |
-
}
|
150 |
-
|
151 |
-
/**
|
152 |
-
* Reposition the methods element
|
153 |
-
*/
|
154 |
-
function setPosition(left, top) {
|
155 |
-
methodsElement.style.left = left + 'px';
|
156 |
-
methodsElement.style.top = top + 'px';
|
157 |
-
}
|
158 |
-
|
159 |
-
/**
|
160 |
-
* Moves the methods the specified delta
|
161 |
-
*/
|
162 |
-
function moveSelected(delta) {
|
163 |
-
setSelectedIndex(selectedIndex + delta);
|
164 |
-
}
|
165 |
-
|
166 |
-
/**
|
167 |
-
* Checks to see if this is visible
|
168 |
-
*/
|
169 |
-
function isVisible() {
|
170 |
-
return visible;
|
171 |
-
}
|
172 |
-
|
173 |
-
/**
|
174 |
-
* Show the methods UI
|
175 |
-
*/
|
176 |
-
function setVisible(b) {
|
177 |
-
visible = b;
|
178 |
-
utils.showElement(methodsElement, b);
|
179 |
-
}
|
180 |
-
|
181 |
-
// arrow click events
|
182 |
-
downArrowElement.onclick = function () {
|
183 |
-
moveSelected(1);
|
184 |
-
};
|
185 |
-
|
186 |
-
// arrow click events
|
187 |
-
upArrowElement.onclick = function () {
|
188 |
-
moveSelected(-1);
|
189 |
-
};
|
190 |
-
|
191 |
-
this.setVisible = setVisible;
|
192 |
-
this.isVisible = isVisible;
|
193 |
-
this.setSelectedIndex = setSelectedIndex;
|
194 |
-
this.setMethods = setMethods;
|
195 |
-
this.moveSelected = moveSelected;
|
196 |
-
this.setPosition = setPosition;
|
197 |
-
};
|
198 |
-
|
199 |
-
var DocumentationSide = function()
|
200 |
-
{
|
201 |
-
var utils = new Utils();
|
202 |
-
var documentationElement = document.getElementById('editor-documentation-side');
|
203 |
-
|
204 |
-
function showElement(b) {
|
205 |
-
if (documentationElement != null)
|
206 |
-
utils.showElement(documentationElement, b);
|
207 |
-
else
|
208 |
-
|
209 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
210 |
-
// parent.postMessage({'action':'showtip', 'visible':b}, "*");
|
211 |
-
// FIXED:
|
212 |
-
|
213 |
-
};
|
214 |
-
|
215 |
-
function showDocumentation(documentation) {
|
216 |
-
if (documentation == null || documentation.trim().length == 0) {
|
217 |
-
showElement(false);
|
218 |
-
}
|
219 |
-
else {
|
220 |
-
showElement(true);
|
221 |
-
if (documentationElement != null)
|
222 |
-
{
|
223 |
-
if (documentation.trim().indexOf("[JAVASCRIPT]") == 0) {
|
224 |
-
eval("(" + documentation.trim().substr("[JAVASCRIPT]".length) + ")")(documentationElement);
|
225 |
-
} else {
|
226 |
-
documentationElement.innerHTML = documentation;
|
227 |
-
}
|
228 |
-
} else {
|
229 |
-
parent.postMessage({'action':'tip', 'html':documentation.trim()}, "*");
|
230 |
-
}
|
231 |
-
}
|
232 |
-
}
|
233 |
-
|
234 |
-
function moveElement(top) {
|
235 |
-
if (documentationElement != null)
|
236 |
-
{
|
237 |
-
var headerHeight = document.getElementById("header").offsetHeight;
|
238 |
-
documentationElement.style.top = (top - headerHeight - 20) + "px";
|
239 |
-
}
|
240 |
-
}
|
241 |
-
|
242 |
-
this.moveElement = moveElement;
|
243 |
-
this.showDocumentation = showDocumentation;
|
244 |
-
this.showElement = showElement;
|
245 |
-
}
|
246 |
-
|
247 |
-
var DeclarationsIntellisense = function () {
|
248 |
-
var events = { itemChosen: [], itemSelected: [] };
|
249 |
-
var utils = new Utils();
|
250 |
-
var selectedIndex = 0;
|
251 |
-
var filteredDeclarations = [];
|
252 |
-
var filteredDeclarationsUI = [];
|
253 |
-
var visible = false;
|
254 |
-
var declarations = [];
|
255 |
-
var documentationSide = new DocumentationSide();
|
256 |
-
|
257 |
-
// ui widgets
|
258 |
-
var selectedElement = null;
|
259 |
-
var listElement = document.createElement('ul');
|
260 |
-
listElement.className = 'br-intellisense';
|
261 |
-
document.body.appendChild(listElement);
|
262 |
-
|
263 |
-
/**
|
264 |
-
* Filters an array
|
265 |
-
*/
|
266 |
-
function filter(arr, cb) {
|
267 |
-
var ret = [];
|
268 |
-
arr.forEach(function (item) {
|
269 |
-
if (cb(item)) {
|
270 |
-
ret.push(item);
|
271 |
-
}
|
272 |
-
});
|
273 |
-
return ret;
|
274 |
-
};
|
275 |
-
|
276 |
-
/**
|
277 |
-
* Triggers that an item is chosen.
|
278 |
-
*/
|
279 |
-
function triggerItemChosen(item) {
|
280 |
-
events.itemChosen.forEach(function (callback) {
|
281 |
-
callback(item);
|
282 |
-
});
|
283 |
-
}
|
284 |
-
|
285 |
-
/**
|
286 |
-
* Triggers that an item is selected.
|
287 |
-
*/
|
288 |
-
function triggerItemSelected(item) {
|
289 |
-
events.itemSelected.forEach(function (callback) {
|
290 |
-
callback(item);
|
291 |
-
});
|
292 |
-
}
|
293 |
-
|
294 |
-
/**
|
295 |
-
* Gets the selected index
|
296 |
-
*/
|
297 |
-
function getSelectedIndex(idx) {
|
298 |
-
return selectedIndex;
|
299 |
-
}
|
300 |
-
|
301 |
-
/**
|
302 |
-
* Sets the selected index
|
303 |
-
*/
|
304 |
-
function setSelectedIndex(idx) {
|
305 |
-
if (idx != selectedIndex) {
|
306 |
-
selectedIndex = idx;
|
307 |
-
triggerItemSelected(getSelectedItem());
|
308 |
-
}
|
309 |
-
}
|
310 |
-
|
311 |
-
/**
|
312 |
-
* Event when an item is chosen (double clicked).
|
313 |
-
*/
|
314 |
-
function onItemChosen(callback) {
|
315 |
-
events.itemChosen.push(callback);
|
316 |
-
}
|
317 |
-
|
318 |
-
/**
|
319 |
-
* Event when an item is selected.
|
320 |
-
*/
|
321 |
-
function onItemSelected(callback) {
|
322 |
-
events.itemSelected.push(callback);
|
323 |
-
}
|
324 |
-
|
325 |
-
/**
|
326 |
-
* Gets the selected item
|
327 |
-
*/
|
328 |
-
function getSelectedItem() {
|
329 |
-
return filteredDeclarations[selectedIndex];
|
330 |
-
}
|
331 |
-
|
332 |
-
/**
|
333 |
-
* Creates a list item that is appended to our intellisense list
|
334 |
-
*/
|
335 |
-
function createListItemDefault(item, idx) {
|
336 |
-
var listItem = document.createElement('li');
|
337 |
-
listItem.innerHTML = '<span class="br-icon icon-glyph-' + item.glyph + '"></span> ' + item.name;
|
338 |
-
listItem.className = 'br-listlink'
|
339 |
-
return listItem;
|
340 |
-
}
|
341 |
-
|
342 |
-
/**
|
343 |
-
* Refreshes the user interface for the selected element
|
344 |
-
*/
|
345 |
-
function refreshSelected() {
|
346 |
-
if (selectedElement != null) {
|
347 |
-
utils.removeCssClass(selectedElement, 'br-selected');
|
348 |
-
}
|
349 |
-
|
350 |
-
selectedElement = filteredDeclarationsUI[selectedIndex];
|
351 |
-
if (selectedElement) {
|
352 |
-
utils.addCssClass(selectedElement, 'br-selected');
|
353 |
-
|
354 |
-
var item = getSelectedItem();
|
355 |
-
documentationSide.showDocumentation(item.documentation);
|
356 |
-
|
357 |
-
var top = selectedElement.offsetTop;
|
358 |
-
var bottom = top + selectedElement.offsetHeight;
|
359 |
-
var scrollTop = listElement.scrollTop;
|
360 |
-
if (top <= scrollTop) {
|
361 |
-
listElement.scrollTop = top;
|
362 |
-
}
|
363 |
-
else if (bottom >= scrollTop + listElement.offsetHeight) {
|
364 |
-
listElement.scrollTop = bottom - listElement.offsetHeight;
|
365 |
-
}
|
366 |
-
}
|
367 |
-
}
|
368 |
-
|
369 |
-
/**
|
370 |
-
* Refreshes the user interface.
|
371 |
-
*/
|
372 |
-
function refreshUI() {
|
373 |
-
listElement.innerHTML = '';
|
374 |
-
filteredDeclarationsUI = [];
|
375 |
-
filteredDeclarations.forEach(function (item, idx) {
|
376 |
-
var listItem = createListItemDefault(item, idx);
|
377 |
-
|
378 |
-
listItem.ondblclick = function () {
|
379 |
-
setSelectedIndex(idx);
|
380 |
-
triggerItemChosen(getSelectedItem());
|
381 |
-
setVisible(false);
|
382 |
-
documentationSide.showElement(false);
|
383 |
-
};
|
384 |
-
|
385 |
-
listItem.onclick = function () {
|
386 |
-
setSelectedIndex(idx);
|
387 |
-
};
|
388 |
-
|
389 |
-
listElement.appendChild(listItem);
|
390 |
-
filteredDeclarationsUI.push(listItem);
|
391 |
-
});
|
392 |
-
|
393 |
-
refreshSelected();
|
394 |
-
}
|
395 |
-
|
396 |
-
/**
|
397 |
-
* Show the auto complete and the documentation elements
|
398 |
-
*/
|
399 |
-
function setVisible(b) {
|
400 |
-
visible = b;
|
401 |
-
utils.showElement(listElement, b);
|
402 |
-
documentationSide.showElement(b);
|
403 |
-
}
|
404 |
-
|
405 |
-
/**
|
406 |
-
* This method is called by the end-user application
|
407 |
-
*/
|
408 |
-
function setDeclarations(data) {
|
409 |
-
if (data != null && data.length > 0) {
|
410 |
-
// set the data
|
411 |
-
declarations = data;
|
412 |
-
filteredDeclarations = data;
|
413 |
-
|
414 |
-
// show the elements
|
415 |
-
setVisible(true);
|
416 |
-
documentationSide.showElement(true);
|
417 |
-
setFilter('');
|
418 |
-
}
|
419 |
-
}
|
420 |
-
|
421 |
-
/**
|
422 |
-
* Sets the position of the list element and documentation element
|
423 |
-
*/
|
424 |
-
function setPosition(left, top) {
|
425 |
-
// reposition intellisense
|
426 |
-
listElement.style.left = left + 'px';
|
427 |
-
listElement.style.top = top + 'px';
|
428 |
-
|
429 |
-
// reposition documentation
|
430 |
-
documentationSide.moveElement(top);
|
431 |
-
}
|
432 |
-
|
433 |
-
/**
|
434 |
-
* Refresh the filter
|
435 |
-
*/
|
436 |
-
function setFilter(filterText) {
|
437 |
-
if (filterText.indexOf("``") == 0)
|
438 |
-
filterText = filterText.substr(2);
|
439 |
-
|
440 |
-
// Only apply the filter if there is something left, otherwise leave unchanged
|
441 |
-
var filteredTemp = filter(declarations, function (x) {
|
442 |
-
return x.name.toLowerCase().indexOf(filterText) === 0;
|
443 |
-
});
|
444 |
-
if (filteredTemp.length > 0)
|
445 |
-
filteredDeclarations = filteredTemp;
|
446 |
-
|
447 |
-
selectedIndex = 0;
|
448 |
-
refreshUI();
|
449 |
-
}
|
450 |
-
|
451 |
-
/**
|
452 |
-
* Moves the auto complete selection up or down a specified amount
|
453 |
-
*/
|
454 |
-
function moveSelected(delta) {
|
455 |
-
var idx = selectedIndex + delta;
|
456 |
-
idx = Math.max(idx, 0);
|
457 |
-
idx = Math.min(idx, filteredDeclarations.length - 1);
|
458 |
-
|
459 |
-
// select
|
460 |
-
setSelectedIndex(idx)
|
461 |
-
refreshSelected();
|
462 |
-
}
|
463 |
-
|
464 |
-
/**
|
465 |
-
* Is the list visible or not
|
466 |
-
*/
|
467 |
-
function isVisible() {
|
468 |
-
return visible;
|
469 |
-
}
|
470 |
-
|
471 |
-
// public API
|
472 |
-
this.isVisible = isVisible;
|
473 |
-
this.setFilter = setFilter;
|
474 |
-
this.getSelectedItem = getSelectedItem;
|
475 |
-
this.getSelectedIndex = getSelectedIndex;
|
476 |
-
this.setSelectedIndex = setSelectedIndex;
|
477 |
-
this.onItemChosen = onItemChosen;
|
478 |
-
this.onItemSelected = onItemSelected;
|
479 |
-
this.moveSelected = moveSelected;
|
480 |
-
this.setDeclarations = setDeclarations;
|
481 |
-
this.setPosition = setPosition;
|
482 |
-
this.setVisible = setVisible;
|
483 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/124.js
DELETED
@@ -1,483 +0,0 @@
|
|
1 |
-
var Utils = function () {
|
2 |
-
/**
|
3 |
-
* Eithers shows the specified element or hides it
|
4 |
-
*/
|
5 |
-
function showElement(el, b) {
|
6 |
-
el.style.display = b ? 'block' : 'none';
|
7 |
-
}
|
8 |
-
|
9 |
-
/**
|
10 |
-
* Check to see if an element has a css class
|
11 |
-
*/
|
12 |
-
function hasCssClass(el, name) {
|
13 |
-
var classes = el.className.split(/\s+/g);
|
14 |
-
return classes.indexOf(name) !== -1;
|
15 |
-
}
|
16 |
-
|
17 |
-
/**
|
18 |
-
* Adds a css class from an element
|
19 |
-
*/
|
20 |
-
function addCssClass(el, name) {
|
21 |
-
if (!hasCssClass(el, name)) {
|
22 |
-
el.className += " " + name;
|
23 |
-
}
|
24 |
-
}
|
25 |
-
|
26 |
-
/**
|
27 |
-
* Removes a css class from an element
|
28 |
-
*/
|
29 |
-
function removeCssClass(el, name) {
|
30 |
-
var classes = el.className.split(/\s+/g);
|
31 |
-
while (true) {
|
32 |
-
var index = classes.indexOf(name);
|
33 |
-
if (index == -1) {
|
34 |
-
break;
|
35 |
-
}
|
36 |
-
classes.splice(index, 1);
|
37 |
-
}
|
38 |
-
el.className = classes.join(" ");
|
39 |
-
}
|
40 |
-
|
41 |
-
/**
|
42 |
-
* Convenience method to get the last index of any of the items in the array
|
43 |
-
*/
|
44 |
-
function lastIndexOfAny(str, arr, start) {
|
45 |
-
var max = -1;
|
46 |
-
for (var i = 0; i < arr.length; i++) {
|
47 |
-
var val = str.lastIndexOf(arr[i], start);
|
48 |
-
max = Math.max(max, val);
|
49 |
-
}
|
50 |
-
return max;
|
51 |
-
}
|
52 |
-
|
53 |
-
function repeat(s, n){
|
54 |
-
var a = [];
|
55 |
-
while(a.length < n){
|
56 |
-
a.push(s);
|
57 |
-
}
|
58 |
-
return a.join('');
|
59 |
-
}
|
60 |
-
|
61 |
-
function escapeIdent(name) {
|
62 |
-
if (!isNaN(name[0]) || lastIndexOfAny(name, [' ', '[', ']', '.']) != -1) {
|
63 |
-
name = '``' + name + '``';
|
64 |
-
}
|
65 |
-
return name;
|
66 |
-
}
|
67 |
-
|
68 |
-
|
69 |
-
this.lastIndexOfAny = lastIndexOfAny;
|
70 |
-
this.removeCssClass = removeCssClass;
|
71 |
-
this.addCssClass = addCssClass;
|
72 |
-
this.hasCssClass = hasCssClass;
|
73 |
-
this.showElement = showElement;
|
74 |
-
this.escapeIdent = escapeIdent;
|
75 |
-
this.repeat = repeat;
|
76 |
-
};
|
77 |
-
|
78 |
-
|
79 |
-
var MethodsIntellisense = function () {
|
80 |
-
var utils = new Utils();
|
81 |
-
var visible = false;
|
82 |
-
var methods = []
|
83 |
-
var selectedIndex = 0;
|
84 |
-
|
85 |
-
// methods
|
86 |
-
var methodsElement = document.createElement('div');
|
87 |
-
methodsElement.className = 'br-methods';
|
88 |
-
|
89 |
-
// methods text
|
90 |
-
var methodsTextElement = document.createElement('div');
|
91 |
-
methodsTextElement.className = 'br-methods-text';
|
92 |
-
|
93 |
-
// arrows
|
94 |
-
var arrowsElement = document.createElement('div');
|
95 |
-
arrowsElement.className = 'br-methods-arrows';
|
96 |
-
|
97 |
-
// up arrow
|
98 |
-
var upArrowElement = document.createElement('span');
|
99 |
-
upArrowElement.className = 'br-methods-arrow';
|
100 |
-
upArrowElement.innerHTML = '↑';
|
101 |
-
|
102 |
-
// down arrow
|
103 |
-
var downArrowElement = document.createElement('span');
|
104 |
-
downArrowElement.className = 'br-methods-arrow';
|
105 |
-
downArrowElement.innerHTML = '↓';
|
106 |
-
|
107 |
-
// arrow text (1 of x)
|
108 |
-
var arrowTextElement = document.createElement('span');
|
109 |
-
arrowTextElement.className = 'br-methods-arrow-text';
|
110 |
-
|
111 |
-
arrowsElement.appendChild(upArrowElement);
|
112 |
-
arrowsElement.appendChild(arrowTextElement);
|
113 |
-
arrowsElement.appendChild(downArrowElement);
|
114 |
-
methodsElement.appendChild(arrowsElement);
|
115 |
-
methodsElement.appendChild(methodsTextElement);
|
116 |
-
document.body.appendChild(methodsElement);
|
117 |
-
|
118 |
-
/**
|
119 |
-
* Sets the selected index of the methods
|
120 |
-
*/
|
121 |
-
function setSelectedIndex(idx) {
|
122 |
-
var disabledColor = '#808080';
|
123 |
-
var enabledColor = 'black';
|
124 |
-
if (idx < 0) {
|
125 |
-
idx = methods.length - 1;
|
126 |
-
}
|
127 |
-
else if (idx >= methods.length) {
|
128 |
-
idx = 0;
|
129 |
-
}
|
130 |
-
|
131 |
-
selectedIndex = idx;
|
132 |
-
methodsTextElement.innerHTML = methods[idx];
|
133 |
-
arrowTextElement.innerHTML = (idx + 1) + ' of ' + methods.length;
|
134 |
-
}
|
135 |
-
|
136 |
-
/**
|
137 |
-
* This method is called by the end-user application to show method information
|
138 |
-
*/
|
139 |
-
function setMethods(data) {
|
140 |
-
if (data != null && data.length > 0) {
|
141 |
-
methods = data;
|
142 |
-
|
143 |
-
// show the elements
|
144 |
-
setVisible(true);
|
145 |
-
|
146 |
-
// show the first item
|
147 |
-
setSelectedIndex(0);
|
148 |
-
}
|
149 |
-
}
|
150 |
-
|
151 |
-
/**
|
152 |
-
* Reposition the methods element
|
153 |
-
*/
|
154 |
-
function setPosition(left, top) {
|
155 |
-
methodsElement.style.left = left + 'px';
|
156 |
-
methodsElement.style.top = top + 'px';
|
157 |
-
}
|
158 |
-
|
159 |
-
/**
|
160 |
-
* Moves the methods the specified delta
|
161 |
-
*/
|
162 |
-
function moveSelected(delta) {
|
163 |
-
setSelectedIndex(selectedIndex + delta);
|
164 |
-
}
|
165 |
-
|
166 |
-
/**
|
167 |
-
* Checks to see if this is visible
|
168 |
-
*/
|
169 |
-
function isVisible() {
|
170 |
-
return visible;
|
171 |
-
}
|
172 |
-
|
173 |
-
/**
|
174 |
-
* Show the methods UI
|
175 |
-
*/
|
176 |
-
function setVisible(b) {
|
177 |
-
visible = b;
|
178 |
-
utils.showElement(methodsElement, b);
|
179 |
-
}
|
180 |
-
|
181 |
-
// arrow click events
|
182 |
-
downArrowElement.onclick = function () {
|
183 |
-
moveSelected(1);
|
184 |
-
};
|
185 |
-
|
186 |
-
// arrow click events
|
187 |
-
upArrowElement.onclick = function () {
|
188 |
-
moveSelected(-1);
|
189 |
-
};
|
190 |
-
|
191 |
-
this.setVisible = setVisible;
|
192 |
-
this.isVisible = isVisible;
|
193 |
-
this.setSelectedIndex = setSelectedIndex;
|
194 |
-
this.setMethods = setMethods;
|
195 |
-
this.moveSelected = moveSelected;
|
196 |
-
this.setPosition = setPosition;
|
197 |
-
};
|
198 |
-
|
199 |
-
var DocumentationSide = function()
|
200 |
-
{
|
201 |
-
var utils = new Utils();
|
202 |
-
var documentationElement = document.getElementById('editor-documentation-side');
|
203 |
-
|
204 |
-
function showElement(b) {
|
205 |
-
if (documentationElement != null)
|
206 |
-
utils.showElement(documentationElement, b);
|
207 |
-
else
|
208 |
-
parent.postMessage({'action':'showtip', 'visible':b}, "*");
|
209 |
-
};
|
210 |
-
|
211 |
-
function showDocumentation(documentation) {
|
212 |
-
if (documentation == null || documentation.trim().length == 0) {
|
213 |
-
showElement(false);
|
214 |
-
}
|
215 |
-
else {
|
216 |
-
showElement(true);
|
217 |
-
if (documentationElement != null)
|
218 |
-
{
|
219 |
-
if (documentation.trim().indexOf("[JAVASCRIPT]") == 0) {
|
220 |
-
eval("(" + documentation.trim().substr("[JAVASCRIPT]".length) + ")")(documentationElement);
|
221 |
-
} else {
|
222 |
-
documentationElement.innerHTML = documentation;
|
223 |
-
}
|
224 |
-
} else {
|
225 |
-
|
226 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
227 |
-
// parent.postMessage({'action':'tip', 'html':documentation.trim()}, "*");
|
228 |
-
// FIXED:
|
229 |
-
|
230 |
-
}
|
231 |
-
}
|
232 |
-
}
|
233 |
-
|
234 |
-
function moveElement(top) {
|
235 |
-
if (documentationElement != null)
|
236 |
-
{
|
237 |
-
var headerHeight = document.getElementById("header").offsetHeight;
|
238 |
-
documentationElement.style.top = (top - headerHeight - 20) + "px";
|
239 |
-
}
|
240 |
-
}
|
241 |
-
|
242 |
-
this.moveElement = moveElement;
|
243 |
-
this.showDocumentation = showDocumentation;
|
244 |
-
this.showElement = showElement;
|
245 |
-
}
|
246 |
-
|
247 |
-
var DeclarationsIntellisense = function () {
|
248 |
-
var events = { itemChosen: [], itemSelected: [] };
|
249 |
-
var utils = new Utils();
|
250 |
-
var selectedIndex = 0;
|
251 |
-
var filteredDeclarations = [];
|
252 |
-
var filteredDeclarationsUI = [];
|
253 |
-
var visible = false;
|
254 |
-
var declarations = [];
|
255 |
-
var documentationSide = new DocumentationSide();
|
256 |
-
|
257 |
-
// ui widgets
|
258 |
-
var selectedElement = null;
|
259 |
-
var listElement = document.createElement('ul');
|
260 |
-
listElement.className = 'br-intellisense';
|
261 |
-
document.body.appendChild(listElement);
|
262 |
-
|
263 |
-
/**
|
264 |
-
* Filters an array
|
265 |
-
*/
|
266 |
-
function filter(arr, cb) {
|
267 |
-
var ret = [];
|
268 |
-
arr.forEach(function (item) {
|
269 |
-
if (cb(item)) {
|
270 |
-
ret.push(item);
|
271 |
-
}
|
272 |
-
});
|
273 |
-
return ret;
|
274 |
-
};
|
275 |
-
|
276 |
-
/**
|
277 |
-
* Triggers that an item is chosen.
|
278 |
-
*/
|
279 |
-
function triggerItemChosen(item) {
|
280 |
-
events.itemChosen.forEach(function (callback) {
|
281 |
-
callback(item);
|
282 |
-
});
|
283 |
-
}
|
284 |
-
|
285 |
-
/**
|
286 |
-
* Triggers that an item is selected.
|
287 |
-
*/
|
288 |
-
function triggerItemSelected(item) {
|
289 |
-
events.itemSelected.forEach(function (callback) {
|
290 |
-
callback(item);
|
291 |
-
});
|
292 |
-
}
|
293 |
-
|
294 |
-
/**
|
295 |
-
* Gets the selected index
|
296 |
-
*/
|
297 |
-
function getSelectedIndex(idx) {
|
298 |
-
return selectedIndex;
|
299 |
-
}
|
300 |
-
|
301 |
-
/**
|
302 |
-
* Sets the selected index
|
303 |
-
*/
|
304 |
-
function setSelectedIndex(idx) {
|
305 |
-
if (idx != selectedIndex) {
|
306 |
-
selectedIndex = idx;
|
307 |
-
triggerItemSelected(getSelectedItem());
|
308 |
-
}
|
309 |
-
}
|
310 |
-
|
311 |
-
/**
|
312 |
-
* Event when an item is chosen (double clicked).
|
313 |
-
*/
|
314 |
-
function onItemChosen(callback) {
|
315 |
-
events.itemChosen.push(callback);
|
316 |
-
}
|
317 |
-
|
318 |
-
/**
|
319 |
-
* Event when an item is selected.
|
320 |
-
*/
|
321 |
-
function onItemSelected(callback) {
|
322 |
-
events.itemSelected.push(callback);
|
323 |
-
}
|
324 |
-
|
325 |
-
/**
|
326 |
-
* Gets the selected item
|
327 |
-
*/
|
328 |
-
function getSelectedItem() {
|
329 |
-
return filteredDeclarations[selectedIndex];
|
330 |
-
}
|
331 |
-
|
332 |
-
/**
|
333 |
-
* Creates a list item that is appended to our intellisense list
|
334 |
-
*/
|
335 |
-
function createListItemDefault(item, idx) {
|
336 |
-
var listItem = document.createElement('li');
|
337 |
-
listItem.innerHTML = '<span class="br-icon icon-glyph-' + item.glyph + '"></span> ' + item.name;
|
338 |
-
listItem.className = 'br-listlink'
|
339 |
-
return listItem;
|
340 |
-
}
|
341 |
-
|
342 |
-
/**
|
343 |
-
* Refreshes the user interface for the selected element
|
344 |
-
*/
|
345 |
-
function refreshSelected() {
|
346 |
-
if (selectedElement != null) {
|
347 |
-
utils.removeCssClass(selectedElement, 'br-selected');
|
348 |
-
}
|
349 |
-
|
350 |
-
selectedElement = filteredDeclarationsUI[selectedIndex];
|
351 |
-
if (selectedElement) {
|
352 |
-
utils.addCssClass(selectedElement, 'br-selected');
|
353 |
-
|
354 |
-
var item = getSelectedItem();
|
355 |
-
documentationSide.showDocumentation(item.documentation);
|
356 |
-
|
357 |
-
var top = selectedElement.offsetTop;
|
358 |
-
var bottom = top + selectedElement.offsetHeight;
|
359 |
-
var scrollTop = listElement.scrollTop;
|
360 |
-
if (top <= scrollTop) {
|
361 |
-
listElement.scrollTop = top;
|
362 |
-
}
|
363 |
-
else if (bottom >= scrollTop + listElement.offsetHeight) {
|
364 |
-
listElement.scrollTop = bottom - listElement.offsetHeight;
|
365 |
-
}
|
366 |
-
}
|
367 |
-
}
|
368 |
-
|
369 |
-
/**
|
370 |
-
* Refreshes the user interface.
|
371 |
-
*/
|
372 |
-
function refreshUI() {
|
373 |
-
listElement.innerHTML = '';
|
374 |
-
filteredDeclarationsUI = [];
|
375 |
-
filteredDeclarations.forEach(function (item, idx) {
|
376 |
-
var listItem = createListItemDefault(item, idx);
|
377 |
-
|
378 |
-
listItem.ondblclick = function () {
|
379 |
-
setSelectedIndex(idx);
|
380 |
-
triggerItemChosen(getSelectedItem());
|
381 |
-
setVisible(false);
|
382 |
-
documentationSide.showElement(false);
|
383 |
-
};
|
384 |
-
|
385 |
-
listItem.onclick = function () {
|
386 |
-
setSelectedIndex(idx);
|
387 |
-
};
|
388 |
-
|
389 |
-
listElement.appendChild(listItem);
|
390 |
-
filteredDeclarationsUI.push(listItem);
|
391 |
-
});
|
392 |
-
|
393 |
-
refreshSelected();
|
394 |
-
}
|
395 |
-
|
396 |
-
/**
|
397 |
-
* Show the auto complete and the documentation elements
|
398 |
-
*/
|
399 |
-
function setVisible(b) {
|
400 |
-
visible = b;
|
401 |
-
utils.showElement(listElement, b);
|
402 |
-
documentationSide.showElement(b);
|
403 |
-
}
|
404 |
-
|
405 |
-
/**
|
406 |
-
* This method is called by the end-user application
|
407 |
-
*/
|
408 |
-
function setDeclarations(data) {
|
409 |
-
if (data != null && data.length > 0) {
|
410 |
-
// set the data
|
411 |
-
declarations = data;
|
412 |
-
filteredDeclarations = data;
|
413 |
-
|
414 |
-
// show the elements
|
415 |
-
setVisible(true);
|
416 |
-
documentationSide.showElement(true);
|
417 |
-
setFilter('');
|
418 |
-
}
|
419 |
-
}
|
420 |
-
|
421 |
-
/**
|
422 |
-
* Sets the position of the list element and documentation element
|
423 |
-
*/
|
424 |
-
function setPosition(left, top) {
|
425 |
-
// reposition intellisense
|
426 |
-
listElement.style.left = left + 'px';
|
427 |
-
listElement.style.top = top + 'px';
|
428 |
-
|
429 |
-
// reposition documentation
|
430 |
-
documentationSide.moveElement(top);
|
431 |
-
}
|
432 |
-
|
433 |
-
/**
|
434 |
-
* Refresh the filter
|
435 |
-
*/
|
436 |
-
function setFilter(filterText) {
|
437 |
-
if (filterText.indexOf("``") == 0)
|
438 |
-
filterText = filterText.substr(2);
|
439 |
-
|
440 |
-
// Only apply the filter if there is something left, otherwise leave unchanged
|
441 |
-
var filteredTemp = filter(declarations, function (x) {
|
442 |
-
return x.name.toLowerCase().indexOf(filterText) === 0;
|
443 |
-
});
|
444 |
-
if (filteredTemp.length > 0)
|
445 |
-
filteredDeclarations = filteredTemp;
|
446 |
-
|
447 |
-
selectedIndex = 0;
|
448 |
-
refreshUI();
|
449 |
-
}
|
450 |
-
|
451 |
-
/**
|
452 |
-
* Moves the auto complete selection up or down a specified amount
|
453 |
-
*/
|
454 |
-
function moveSelected(delta) {
|
455 |
-
var idx = selectedIndex + delta;
|
456 |
-
idx = Math.max(idx, 0);
|
457 |
-
idx = Math.min(idx, filteredDeclarations.length - 1);
|
458 |
-
|
459 |
-
// select
|
460 |
-
setSelectedIndex(idx)
|
461 |
-
refreshSelected();
|
462 |
-
}
|
463 |
-
|
464 |
-
/**
|
465 |
-
* Is the list visible or not
|
466 |
-
*/
|
467 |
-
function isVisible() {
|
468 |
-
return visible;
|
469 |
-
}
|
470 |
-
|
471 |
-
// public API
|
472 |
-
this.isVisible = isVisible;
|
473 |
-
this.setFilter = setFilter;
|
474 |
-
this.getSelectedItem = getSelectedItem;
|
475 |
-
this.getSelectedIndex = getSelectedIndex;
|
476 |
-
this.setSelectedIndex = setSelectedIndex;
|
477 |
-
this.onItemChosen = onItemChosen;
|
478 |
-
this.onItemSelected = onItemSelected;
|
479 |
-
this.moveSelected = moveSelected;
|
480 |
-
this.setDeclarations = setDeclarations;
|
481 |
-
this.setPosition = setPosition;
|
482 |
-
this.setVisible = setVisible;
|
483 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/125.js
DELETED
@@ -1,2364 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
* QUnit - A JavaScript Unit Testing Framework
|
3 |
-
*
|
4 |
-
* http://docs.jquery.com/QUnit
|
5 |
-
*
|
6 |
-
* Copyright (c) 2009 John Resig, Jörn Zaefferer
|
7 |
-
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
8 |
-
* and GPL (GPL-LICENSE.txt) licenses.
|
9 |
-
*/
|
10 |
-
|
11 |
-
(function(window) {
|
12 |
-
|
13 |
-
var QUnit = {
|
14 |
-
|
15 |
-
// Initialize the configuration options
|
16 |
-
init: function init() {
|
17 |
-
config = {
|
18 |
-
stats: { all: 0, bad: 0 },
|
19 |
-
moduleStats: { all: 0, bad: 0 },
|
20 |
-
started: +new Date,
|
21 |
-
blocking: false,
|
22 |
-
autorun: false,
|
23 |
-
assertions: [],
|
24 |
-
filters: [],
|
25 |
-
queue: []
|
26 |
-
};
|
27 |
-
|
28 |
-
var tests = id("qunit-tests"),
|
29 |
-
banner = id("qunit-banner"),
|
30 |
-
result = id("qunit-testresult");
|
31 |
-
|
32 |
-
if ( tests ) {
|
33 |
-
tests.innerHTML = "";
|
34 |
-
}
|
35 |
-
|
36 |
-
if ( banner ) {
|
37 |
-
banner.className = "";
|
38 |
-
}
|
39 |
-
|
40 |
-
if ( result ) {
|
41 |
-
result.parentNode.removeChild( result );
|
42 |
-
}
|
43 |
-
},
|
44 |
-
|
45 |
-
// call on start of module test to prepend name to all tests
|
46 |
-
module: function module(name, testEnvironment) {
|
47 |
-
|
48 |
-
synchronize(function() {
|
49 |
-
if ( config.currentModule ) {
|
50 |
-
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
|
51 |
-
}
|
52 |
-
|
53 |
-
config.currentModule = name;
|
54 |
-
config.moduleTestEnvironment = testEnvironment;
|
55 |
-
config.moduleStats = { all: 0, bad: 0 };
|
56 |
-
|
57 |
-
QUnit.moduleStart( name, testEnvironment );
|
58 |
-
});
|
59 |
-
},
|
60 |
-
|
61 |
-
asyncTest: function asyncTest(testName, expected, callback) {
|
62 |
-
if ( arguments.length === 2 ) {
|
63 |
-
callback = expected;
|
64 |
-
expected = 0;
|
65 |
-
}
|
66 |
-
|
67 |
-
QUnit.test(testName, expected, callback, true);
|
68 |
-
},
|
69 |
-
|
70 |
-
test: function test(testName, expected, callback, async) {
|
71 |
-
var name = testName, testEnvironment = {};
|
72 |
-
|
73 |
-
if ( arguments.length === 2 ) {
|
74 |
-
callback = expected;
|
75 |
-
expected = null;
|
76 |
-
}
|
77 |
-
|
78 |
-
if ( config.currentModule ) {
|
79 |
-
name = config.currentModule + " module: " + name;
|
80 |
-
}
|
81 |
-
|
82 |
-
if ( !validTest(name) ) {
|
83 |
-
return;
|
84 |
-
}
|
85 |
-
|
86 |
-
synchronize(function() {
|
87 |
-
QUnit.testStart( testName );
|
88 |
-
|
89 |
-
testEnvironment = extend({
|
90 |
-
setup: function() {},
|
91 |
-
teardown: function() {}
|
92 |
-
}, config.moduleTestEnvironment);
|
93 |
-
|
94 |
-
config.assertions = [];
|
95 |
-
config.expected = null;
|
96 |
-
|
97 |
-
if ( arguments.length >= 3 ) {
|
98 |
-
config.expected = callback;
|
99 |
-
callback = arguments[2];
|
100 |
-
}
|
101 |
-
|
102 |
-
try {
|
103 |
-
if ( !config.pollution ) {
|
104 |
-
saveGlobal();
|
105 |
-
}
|
106 |
-
|
107 |
-
testEnvironment.setup.call(testEnvironment);
|
108 |
-
} catch(e) {
|
109 |
-
QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
|
110 |
-
}
|
111 |
-
|
112 |
-
if ( async ) {
|
113 |
-
QUnit.stop();
|
114 |
-
}
|
115 |
-
|
116 |
-
try {
|
117 |
-
callback.call(testEnvironment);
|
118 |
-
} catch(e) {
|
119 |
-
fail("Test " + name + " died, exception and test follows", e, callback);
|
120 |
-
QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
|
121 |
-
// else next test will carry the responsibility
|
122 |
-
saveGlobal();
|
123 |
-
|
124 |
-
// Restart the tests if they're blocking
|
125 |
-
if ( config.blocking ) {
|
126 |
-
start();
|
127 |
-
}
|
128 |
-
}
|
129 |
-
});
|
130 |
-
|
131 |
-
synchronize(function() {
|
132 |
-
try {
|
133 |
-
checkPollution();
|
134 |
-
testEnvironment.teardown.call(testEnvironment);
|
135 |
-
} catch(e) {
|
136 |
-
QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
|
137 |
-
}
|
138 |
-
|
139 |
-
try {
|
140 |
-
QUnit.reset();
|
141 |
-
} catch(e) {
|
142 |
-
fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
|
143 |
-
}
|
144 |
-
|
145 |
-
if ( config.expected && config.expected != config.assertions.length ) {
|
146 |
-
QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
|
147 |
-
}
|
148 |
-
|
149 |
-
var good = 0, bad = 0,
|
150 |
-
tests = id("qunit-tests");
|
151 |
-
|
152 |
-
config.stats.all += config.assertions.length;
|
153 |
-
config.moduleStats.all += config.assertions.length;
|
154 |
-
|
155 |
-
if ( tests ) {
|
156 |
-
var ol = document.createElement("ol");
|
157 |
-
ol.style.display = "none";
|
158 |
-
|
159 |
-
for ( var i = 0; i < config.assertions.length; i++ ) {
|
160 |
-
var assertion = config.assertions[i];
|
161 |
-
|
162 |
-
var li = document.createElement("li");
|
163 |
-
li.className = assertion.result ? "pass" : "fail";
|
164 |
-
li.innerHTML = assertion.message || "(no message)";
|
165 |
-
ol.appendChild( li );
|
166 |
-
|
167 |
-
if ( assertion.result ) {
|
168 |
-
good++;
|
169 |
-
} else {
|
170 |
-
bad++;
|
171 |
-
config.stats.bad++;
|
172 |
-
config.moduleStats.bad++;
|
173 |
-
}
|
174 |
-
}
|
175 |
-
|
176 |
-
var b = document.createElement("strong");
|
177 |
-
b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
|
178 |
-
|
179 |
-
addEvent(b, "click", function() {
|
180 |
-
var next = b.nextSibling, display = next.style.display;
|
181 |
-
next.style.display = display === "none" ? "block" : "none";
|
182 |
-
});
|
183 |
-
|
184 |
-
addEvent(b, "dblclick", function(e) {
|
185 |
-
var target = (e || window.event).target;
|
186 |
-
if ( target.nodeName.toLowerCase() === "strong" ) {
|
187 |
-
var text = "", node = target.firstChild;
|
188 |
-
|
189 |
-
while ( node.nodeType === 3 ) {
|
190 |
-
text += node.nodeValue;
|
191 |
-
node = node.nextSibling;
|
192 |
-
}
|
193 |
-
|
194 |
-
text = text.replace(/(^\s*|\s*$)/g, "");
|
195 |
-
|
196 |
-
if ( window.location ) {
|
197 |
-
window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
|
198 |
-
}
|
199 |
-
}
|
200 |
-
});
|
201 |
-
|
202 |
-
var li = document.createElement("li");
|
203 |
-
li.className = bad ? "fail" : "pass";
|
204 |
-
li.appendChild( b );
|
205 |
-
li.appendChild( ol );
|
206 |
-
tests.appendChild( li );
|
207 |
-
|
208 |
-
if ( bad ) {
|
209 |
-
var toolbar = id("qunit-testrunner-toolbar");
|
210 |
-
if ( toolbar ) {
|
211 |
-
toolbar.style.display = "block";
|
212 |
-
id("qunit-filter-pass").disabled = null;
|
213 |
-
id("qunit-filter-missing").disabled = null;
|
214 |
-
}
|
215 |
-
}
|
216 |
-
|
217 |
-
} else {
|
218 |
-
for ( var i = 0; i < config.assertions.length; i++ ) {
|
219 |
-
if ( !config.assertions[i].result ) {
|
220 |
-
bad++;
|
221 |
-
config.stats.bad++;
|
222 |
-
config.moduleStats.bad++;
|
223 |
-
}
|
224 |
-
}
|
225 |
-
}
|
226 |
-
|
227 |
-
QUnit.testDone( testName, bad, config.assertions.length );
|
228 |
-
|
229 |
-
if ( !window.setTimeout && !config.queue.length ) {
|
230 |
-
done();
|
231 |
-
}
|
232 |
-
});
|
233 |
-
|
234 |
-
if ( window.setTimeout && !config.doneTimer ) {
|
235 |
-
config.doneTimer = window.setTimeout(function(){
|
236 |
-
if ( !config.queue.length ) {
|
237 |
-
done();
|
238 |
-
} else {
|
239 |
-
synchronize( done );
|
240 |
-
}
|
241 |
-
}, 13);
|
242 |
-
}
|
243 |
-
},
|
244 |
-
|
245 |
-
/**
|
246 |
-
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
|
247 |
-
*/
|
248 |
-
expect: function expect(asserts) {
|
249 |
-
config.expected = asserts;
|
250 |
-
},
|
251 |
-
|
252 |
-
/**
|
253 |
-
* Asserts true.
|
254 |
-
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
|
255 |
-
*/
|
256 |
-
ok: function ok(a, msg) {
|
257 |
-
QUnit.log(a, msg);
|
258 |
-
|
259 |
-
config.assertions.push({
|
260 |
-
result: !!a,
|
261 |
-
message: msg
|
262 |
-
});
|
263 |
-
},
|
264 |
-
|
265 |
-
/**
|
266 |
-
* Checks that the first two arguments are equal, with an optional message.
|
267 |
-
* Prints out both actual and expected values.
|
268 |
-
*
|
269 |
-
* Prefered to ok( actual == expected, message )
|
270 |
-
*
|
271 |
-
* @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." );
|
272 |
-
*
|
273 |
-
* @param Object actual
|
274 |
-
* @param Object expected
|
275 |
-
* @param String message (optional)
|
276 |
-
*/
|
277 |
-
equals: function equals(actual, expected, message) {
|
278 |
-
push(expected == actual, actual, expected, message);
|
279 |
-
},
|
280 |
-
|
281 |
-
same: function(a, b, message) {
|
282 |
-
push(QUnit.equiv(a, b), a, b, message);
|
283 |
-
},
|
284 |
-
|
285 |
-
start: function start() {
|
286 |
-
// A slight delay, to avoid any current callbacks
|
287 |
-
if ( window.setTimeout ) {
|
288 |
-
window.setTimeout(function() {
|
289 |
-
if ( config.timeout ) {
|
290 |
-
clearTimeout(config.timeout);
|
291 |
-
}
|
292 |
-
|
293 |
-
config.blocking = false;
|
294 |
-
process();
|
295 |
-
}, 13);
|
296 |
-
} else {
|
297 |
-
config.blocking = false;
|
298 |
-
process();
|
299 |
-
}
|
300 |
-
},
|
301 |
-
|
302 |
-
stop: function stop(timeout) {
|
303 |
-
config.blocking = true;
|
304 |
-
|
305 |
-
if ( timeout && window.setTimeout ) {
|
306 |
-
config.timeout = window.setTimeout(function() {
|
307 |
-
QUnit.ok( false, "Test timed out" );
|
308 |
-
QUnit.start();
|
309 |
-
}, timeout);
|
310 |
-
}
|
311 |
-
},
|
312 |
-
|
313 |
-
/**
|
314 |
-
* Resets the test setup. Useful for tests that modify the DOM.
|
315 |
-
*/
|
316 |
-
reset: function reset() {
|
317 |
-
if ( window.jQuery ) {
|
318 |
-
jQuery("#main").html( config.fixture );
|
319 |
-
jQuery.event.global = {};
|
320 |
-
jQuery.ajaxSettings = extend({}, config.ajaxSettings);
|
321 |
-
}
|
322 |
-
},
|
323 |
-
|
324 |
-
/**
|
325 |
-
* Trigger an event on an element.
|
326 |
-
*
|
327 |
-
* @example triggerEvent( document.body, "click" );
|
328 |
-
*
|
329 |
-
* @param DOMElement elem
|
330 |
-
* @param String type
|
331 |
-
*/
|
332 |
-
triggerEvent: function triggerEvent( elem, type, event ) {
|
333 |
-
if ( document.createEvent ) {
|
334 |
-
event = document.createEvent("MouseEvents");
|
335 |
-
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
|
336 |
-
0, 0, 0, 0, 0, false, false, false, false, 0, null);
|
337 |
-
elem.dispatchEvent( event );
|
338 |
-
|
339 |
-
} else if ( elem.fireEvent ) {
|
340 |
-
elem.fireEvent("on"+type);
|
341 |
-
}
|
342 |
-
},
|
343 |
-
|
344 |
-
// Logging callbacks
|
345 |
-
done: function done(failures, total) {},
|
346 |
-
log: function log(result, message) {},
|
347 |
-
testStart: function testStart(name) {},
|
348 |
-
testDone: function testDone(name, failures, total) {},
|
349 |
-
moduleStart: function moduleStart(name, testEnvironment) {},
|
350 |
-
moduleDone: function moduleDone(name, failures, total) {}
|
351 |
-
};
|
352 |
-
|
353 |
-
// Maintain internal state
|
354 |
-
var config = {
|
355 |
-
// The queue of tests to run
|
356 |
-
queue: [],
|
357 |
-
|
358 |
-
// block until document ready
|
359 |
-
blocking: true
|
360 |
-
};
|
361 |
-
|
362 |
-
// Load paramaters
|
363 |
-
(function() {
|
364 |
-
var location = window.location || { search: "", protocol: "file:" },
|
365 |
-
GETParams = location.search.slice(1).split('&');
|
366 |
-
|
367 |
-
for ( var i = 0; i < GETParams.length; i++ ) {
|
368 |
-
GETParams[i] = decodeURIComponent( GETParams[i] );
|
369 |
-
if ( GETParams[i] === "noglobals" ) {
|
370 |
-
GETParams.splice( i, 1 );
|
371 |
-
i--;
|
372 |
-
config.noglobals = true;
|
373 |
-
}
|
374 |
-
}
|
375 |
-
|
376 |
-
// restrict modules/tests by get parameters
|
377 |
-
config.filters = GETParams;
|
378 |
-
|
379 |
-
// Figure out if we're running the tests from a server or not
|
380 |
-
QUnit.isLocal = !!(location.protocol === 'file:');
|
381 |
-
})();
|
382 |
-
|
383 |
-
// Expose the API as global variables, unless an 'exports'
|
384 |
-
// object exists, in that case we assume we're in CommonJS
|
385 |
-
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
|
386 |
-
extend(window, QUnit);
|
387 |
-
window.QUnit = QUnit;
|
388 |
-
} else {
|
389 |
-
extend(exports, QUnit);
|
390 |
-
exports.QUnit = QUnit;
|
391 |
-
}
|
392 |
-
|
393 |
-
if ( typeof document === "undefined" || document.readyState === "complete" ) {
|
394 |
-
config.autorun = true;
|
395 |
-
}
|
396 |
-
|
397 |
-
addEvent(window, "load", function() {
|
398 |
-
// Initialize the config, saving the execution queue
|
399 |
-
var oldconfig = extend({}, config);
|
400 |
-
QUnit.init();
|
401 |
-
extend(config, oldconfig);
|
402 |
-
|
403 |
-
config.blocking = false;
|
404 |
-
|
405 |
-
var userAgent = id("qunit-userAgent");
|
406 |
-
if ( userAgent ) {
|
407 |
-
userAgent.innerHTML = navigator.userAgent;
|
408 |
-
}
|
409 |
-
|
410 |
-
var toolbar = id("qunit-testrunner-toolbar");
|
411 |
-
if ( toolbar ) {
|
412 |
-
toolbar.style.display = "none";
|
413 |
-
|
414 |
-
var filter = document.createElement("input");
|
415 |
-
filter.type = "checkbox";
|
416 |
-
filter.id = "qunit-filter-pass";
|
417 |
-
filter.disabled = true;
|
418 |
-
addEvent( filter, "click", function() {
|
419 |
-
var li = document.getElementsByTagName("li");
|
420 |
-
for ( var i = 0; i < li.length; i++ ) {
|
421 |
-
if ( li[i].className.indexOf("pass") > -1 ) {
|
422 |
-
li[i].style.display = filter.checked ? "none" : "block";
|
423 |
-
}
|
424 |
-
}
|
425 |
-
});
|
426 |
-
toolbar.appendChild( filter );
|
427 |
-
|
428 |
-
var label = document.createElement("label");
|
429 |
-
label.setAttribute("for", "filter-pass");
|
430 |
-
label.innerHTML = "Hide passed tests";
|
431 |
-
toolbar.appendChild( label );
|
432 |
-
|
433 |
-
var missing = document.createElement("input");
|
434 |
-
missing.type = "checkbox";
|
435 |
-
missing.id = "qunit-filter-missing";
|
436 |
-
missing.disabled = true;
|
437 |
-
addEvent( missing, "click", function() {
|
438 |
-
var li = document.getElementsByTagName("li");
|
439 |
-
for ( var i = 0; i < li.length; i++ ) {
|
440 |
-
if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
|
441 |
-
li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
|
442 |
-
}
|
443 |
-
}
|
444 |
-
});
|
445 |
-
toolbar.appendChild( missing );
|
446 |
-
|
447 |
-
label = document.createElement("label");
|
448 |
-
label.setAttribute("for", "filter-missing");
|
449 |
-
label.innerHTML = "Hide missing tests (untested code is broken code)";
|
450 |
-
toolbar.appendChild( label );
|
451 |
-
}
|
452 |
-
|
453 |
-
var main = id('main');
|
454 |
-
if ( main ) {
|
455 |
-
config.fixture = main.innerHTML;
|
456 |
-
}
|
457 |
-
|
458 |
-
if ( window.jQuery ) {
|
459 |
-
config.ajaxSettings = window.jQuery.ajaxSettings;
|
460 |
-
}
|
461 |
-
|
462 |
-
QUnit.start();
|
463 |
-
});
|
464 |
-
|
465 |
-
function done() {
|
466 |
-
if ( config.doneTimer && window.clearTimeout ) {
|
467 |
-
window.clearTimeout( config.doneTimer );
|
468 |
-
config.doneTimer = null;
|
469 |
-
}
|
470 |
-
|
471 |
-
if ( config.queue.length ) {
|
472 |
-
config.doneTimer = window.setTimeout(function(){
|
473 |
-
if ( !config.queue.length ) {
|
474 |
-
done();
|
475 |
-
} else {
|
476 |
-
synchronize( done );
|
477 |
-
}
|
478 |
-
}, 13);
|
479 |
-
|
480 |
-
return;
|
481 |
-
}
|
482 |
-
|
483 |
-
config.autorun = true;
|
484 |
-
|
485 |
-
// Log the last module results
|
486 |
-
if ( config.currentModule ) {
|
487 |
-
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
|
488 |
-
}
|
489 |
-
|
490 |
-
var banner = id("qunit-banner"),
|
491 |
-
tests = id("qunit-tests"),
|
492 |
-
html = ['Tests completed in ',
|
493 |
-
+new Date - config.started, ' milliseconds.<br/>',
|
494 |
-
'<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('');
|
495 |
-
|
496 |
-
if ( banner ) {
|
497 |
-
banner.className += " " + (config.stats.bad ? "fail" : "pass");
|
498 |
-
}
|
499 |
-
|
500 |
-
if ( tests ) {
|
501 |
-
var result = id("qunit-testresult");
|
502 |
-
|
503 |
-
if ( !result ) {
|
504 |
-
result = document.createElement("p");
|
505 |
-
result.id = "qunit-testresult";
|
506 |
-
result.className = "result";
|
507 |
-
tests.parentNode.insertBefore( result, tests.nextSibling );
|
508 |
-
}
|
509 |
-
|
510 |
-
result.innerHTML = html;
|
511 |
-
}
|
512 |
-
|
513 |
-
QUnit.done( config.stats.bad, config.stats.all );
|
514 |
-
}
|
515 |
-
|
516 |
-
function validTest( name ) {
|
517 |
-
var i = config.filters.length,
|
518 |
-
run = false;
|
519 |
-
|
520 |
-
if ( !i ) {
|
521 |
-
return true;
|
522 |
-
}
|
523 |
-
|
524 |
-
while ( i-- ) {
|
525 |
-
var filter = config.filters[i],
|
526 |
-
not = filter.charAt(0) == '!';
|
527 |
-
|
528 |
-
if ( not ) {
|
529 |
-
filter = filter.slice(1);
|
530 |
-
}
|
531 |
-
|
532 |
-
if ( name.indexOf(filter) !== -1 ) {
|
533 |
-
return !not;
|
534 |
-
}
|
535 |
-
|
536 |
-
if ( not ) {
|
537 |
-
run = true;
|
538 |
-
}
|
539 |
-
}
|
540 |
-
|
541 |
-
return run;
|
542 |
-
}
|
543 |
-
|
544 |
-
function push(result, actual, expected, message) {
|
545 |
-
message = message || (result ? "okay" : "failed");
|
546 |
-
QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
|
547 |
-
}
|
548 |
-
|
549 |
-
function synchronize( callback ) {
|
550 |
-
config.queue.push( callback );
|
551 |
-
|
552 |
-
if ( config.autorun && !config.blocking ) {
|
553 |
-
process();
|
554 |
-
}
|
555 |
-
}
|
556 |
-
|
557 |
-
function process() {
|
558 |
-
while ( config.queue.length && !config.blocking ) {
|
559 |
-
config.queue.shift()();
|
560 |
-
}
|
561 |
-
}
|
562 |
-
|
563 |
-
function saveGlobal() {
|
564 |
-
config.pollution = [];
|
565 |
-
|
566 |
-
if ( config.noglobals ) {
|
567 |
-
for ( var key in window ) {
|
568 |
-
config.pollution.push( key );
|
569 |
-
}
|
570 |
-
}
|
571 |
-
}
|
572 |
-
|
573 |
-
function checkPollution( name ) {
|
574 |
-
var old = config.pollution;
|
575 |
-
saveGlobal();
|
576 |
-
|
577 |
-
var newGlobals = diff( old, config.pollution );
|
578 |
-
if ( newGlobals.length > 0 ) {
|
579 |
-
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
|
580 |
-
config.expected++;
|
581 |
-
}
|
582 |
-
|
583 |
-
var deletedGlobals = diff( config.pollution, old );
|
584 |
-
if ( deletedGlobals.length > 0 ) {
|
585 |
-
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
|
586 |
-
config.expected++;
|
587 |
-
}
|
588 |
-
}
|
589 |
-
|
590 |
-
// returns a new Array with the elements that are in a but not in b
|
591 |
-
function diff( a, b ) {
|
592 |
-
var result = a.slice();
|
593 |
-
for ( var i = 0; i < result.length; i++ ) {
|
594 |
-
for ( var j = 0; j < b.length; j++ ) {
|
595 |
-
if ( result[i] === b[j] ) {
|
596 |
-
result.splice(i, 1);
|
597 |
-
i--;
|
598 |
-
break;
|
599 |
-
}
|
600 |
-
}
|
601 |
-
}
|
602 |
-
return result;
|
603 |
-
}
|
604 |
-
|
605 |
-
function fail(message, exception, callback) {
|
606 |
-
if ( typeof console !== "undefined" && console.error && console.warn ) {
|
607 |
-
console.error(message);
|
608 |
-
console.error(exception);
|
609 |
-
console.warn(callback.toString());
|
610 |
-
|
611 |
-
} else if ( window.opera && opera.postError ) {
|
612 |
-
opera.postError(message, exception, callback.toString);
|
613 |
-
}
|
614 |
-
}
|
615 |
-
|
616 |
-
function extend(a, b) {
|
617 |
-
for ( var prop in b ) {
|
618 |
-
a[prop] = b[prop];
|
619 |
-
}
|
620 |
-
|
621 |
-
return a;
|
622 |
-
}
|
623 |
-
|
624 |
-
function addEvent(elem, type, fn) {
|
625 |
-
if ( elem.addEventListener ) {
|
626 |
-
elem.addEventListener( type, fn, false );
|
627 |
-
} else if ( elem.attachEvent ) {
|
628 |
-
elem.attachEvent( "on" + type, fn );
|
629 |
-
} else {
|
630 |
-
fn();
|
631 |
-
}
|
632 |
-
}
|
633 |
-
|
634 |
-
function id(name) {
|
635 |
-
return !!(typeof document !== "undefined" && document && document.getElementById) &&
|
636 |
-
document.getElementById( name );
|
637 |
-
}
|
638 |
-
|
639 |
-
// Test for equality any JavaScript type.
|
640 |
-
// Discussions and reference: http://philrathe.com/articles/equiv
|
641 |
-
// Test suites: http://philrathe.com/tests/equiv
|
642 |
-
// Author: Philippe Rathé <prathe@gmail.com>
|
643 |
-
QUnit.equiv = function () {
|
644 |
-
|
645 |
-
var innerEquiv; // the real equiv function
|
646 |
-
var callers = []; // stack to decide between skip/abort functions
|
647 |
-
|
648 |
-
|
649 |
-
// Determine what is o.
|
650 |
-
function hoozit(o) {
|
651 |
-
if (o.constructor === String) {
|
652 |
-
return "string";
|
653 |
-
|
654 |
-
} else if (o.constructor === Boolean) {
|
655 |
-
return "boolean";
|
656 |
-
|
657 |
-
} else if (o.constructor === Number) {
|
658 |
-
|
659 |
-
if (isNaN(o)) {
|
660 |
-
return "nan";
|
661 |
-
} else {
|
662 |
-
return "number";
|
663 |
-
}
|
664 |
-
|
665 |
-
} else if (typeof o === "undefined") {
|
666 |
-
return "undefined";
|
667 |
-
|
668 |
-
// consider: typeof null === object
|
669 |
-
} else if (o === null) {
|
670 |
-
return "null";
|
671 |
-
|
672 |
-
// consider: typeof [] === object
|
673 |
-
} else if (o instanceof Array) {
|
674 |
-
return "array";
|
675 |
-
|
676 |
-
// consider: typeof new Date() === object
|
677 |
-
} else if (o instanceof Date) {
|
678 |
-
return "date";
|
679 |
-
|
680 |
-
// consider: /./ instanceof Object;
|
681 |
-
// /./ instanceof RegExp;
|
682 |
-
// typeof /./ === "function"; // => false in IE and Opera,
|
683 |
-
// true in FF and Safari
|
684 |
-
} else if (o instanceof RegExp) {
|
685 |
-
return "regexp";
|
686 |
-
|
687 |
-
} else if (typeof o === "object") {
|
688 |
-
return "object";
|
689 |
-
|
690 |
-
} else if (o instanceof Function) {
|
691 |
-
return "function";
|
692 |
-
} else {
|
693 |
-
return undefined;
|
694 |
-
}
|
695 |
-
}
|
696 |
-
|
697 |
-
// Call the o related callback with the given arguments.
|
698 |
-
function handleEvents(o, callbacks, args) {
|
699 |
-
var prop = hoozit(o);
|
700 |
-
if (prop) {
|
701 |
-
if (hoozit(callbacks[prop]) === "function") {
|
702 |
-
return callbacks[prop].apply(callbacks, args);
|
703 |
-
} else {
|
704 |
-
return callbacks[prop]; // or undefined
|
705 |
-
}
|
706 |
-
}
|
707 |
-
}
|
708 |
-
|
709 |
-
var callbacks = function () {
|
710 |
-
|
711 |
-
// for string, boolean, number and null
|
712 |
-
function useStrictEquality(b, a) {
|
713 |
-
if (b instanceof a.constructor || a instanceof b.constructor) {
|
714 |
-
// to catch short annotaion VS 'new' annotation of a declaration
|
715 |
-
// e.g. var i = 1;
|
716 |
-
// var j = new Number(1);
|
717 |
-
return a == b;
|
718 |
-
} else {
|
719 |
-
return a === b;
|
720 |
-
}
|
721 |
-
}
|
722 |
-
|
723 |
-
return {
|
724 |
-
"string": useStrictEquality,
|
725 |
-
"boolean": useStrictEquality,
|
726 |
-
"number": useStrictEquality,
|
727 |
-
"null": useStrictEquality,
|
728 |
-
"undefined": useStrictEquality,
|
729 |
-
|
730 |
-
"nan": function (b) {
|
731 |
-
return isNaN(b);
|
732 |
-
},
|
733 |
-
|
734 |
-
"date": function (b, a) {
|
735 |
-
return hoozit(b) === "date" && a.valueOf() === b.valueOf();
|
736 |
-
},
|
737 |
-
|
738 |
-
"regexp": function (b, a) {
|
739 |
-
return hoozit(b) === "regexp" &&
|
740 |
-
a.source === b.source && // the regex itself
|
741 |
-
a.global === b.global && // and its modifers (gmi) ...
|
742 |
-
a.ignoreCase === b.ignoreCase &&
|
743 |
-
a.multiline === b.multiline;
|
744 |
-
},
|
745 |
-
|
746 |
-
// - skip when the property is a method of an instance (OOP)
|
747 |
-
// - abort otherwise,
|
748 |
-
// initial === would have catch identical references anyway
|
749 |
-
"function": function () {
|
750 |
-
var caller = callers[callers.length - 1];
|
751 |
-
return caller !== Object &&
|
752 |
-
typeof caller !== "undefined";
|
753 |
-
},
|
754 |
-
|
755 |
-
"array": function (b, a) {
|
756 |
-
var i;
|
757 |
-
var len;
|
758 |
-
|
759 |
-
// b could be an object literal here
|
760 |
-
if ( ! (hoozit(b) === "array")) {
|
761 |
-
return false;
|
762 |
-
}
|
763 |
-
|
764 |
-
len = a.length;
|
765 |
-
if (len !== b.length) { // safe and faster
|
766 |
-
return false;
|
767 |
-
}
|
768 |
-
for (i = 0; i < len; i++) {
|
769 |
-
if ( ! innerEquiv(a[i], b[i])) {
|
770 |
-
return false;
|
771 |
-
}
|
772 |
-
}
|
773 |
-
return true;
|
774 |
-
},
|
775 |
-
|
776 |
-
"object": function (b, a) {
|
777 |
-
var i;
|
778 |
-
var eq = true; // unless we can proove it
|
779 |
-
var aProperties = [], bProperties = []; // collection of strings
|
780 |
-
|
781 |
-
// comparing constructors is more strict than using instanceof
|
782 |
-
if ( a.constructor !== b.constructor) {
|
783 |
-
return false;
|
784 |
-
}
|
785 |
-
|
786 |
-
// stack constructor before traversing properties
|
787 |
-
callers.push(a.constructor);
|
788 |
-
|
789 |
-
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
|
790 |
-
|
791 |
-
aProperties.push(i); // collect a's properties
|
792 |
-
|
793 |
-
if ( ! innerEquiv(a[i], b[i])) {
|
794 |
-
eq = false;
|
795 |
-
}
|
796 |
-
}
|
797 |
-
|
798 |
-
callers.pop(); // unstack, we are done
|
799 |
-
|
800 |
-
for (i in b) {
|
801 |
-
bProperties.push(i); // collect b's properties
|
802 |
-
}
|
803 |
-
|
804 |
-
// Ensures identical properties name
|
805 |
-
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
|
806 |
-
}
|
807 |
-
};
|
808 |
-
}();
|
809 |
-
|
810 |
-
innerEquiv = function () { // can take multiple arguments
|
811 |
-
var args = Array.prototype.slice.apply(arguments);
|
812 |
-
if (args.length < 2) {
|
813 |
-
return true; // end transition
|
814 |
-
}
|
815 |
-
|
816 |
-
return (function (a, b) {
|
817 |
-
if (a === b) {
|
818 |
-
return true; // catch the most you can
|
819 |
-
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
|
820 |
-
return false; // don't lose time with error prone cases
|
821 |
-
} else {
|
822 |
-
return handleEvents(a, callbacks, [b, a]);
|
823 |
-
}
|
824 |
-
|
825 |
-
// apply transition with (1..n) arguments
|
826 |
-
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
|
827 |
-
};
|
828 |
-
|
829 |
-
return innerEquiv;
|
830 |
-
|
831 |
-
}();
|
832 |
-
|
833 |
-
/**
|
834 |
-
* jsDump
|
835 |
-
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
|
836 |
-
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
|
837 |
-
* Date: 5/15/2008
|
838 |
-
* @projectDescription Advanced and extensible data dumping for Javascript.
|
839 |
-
* @version 1.0.0
|
840 |
-
* @author Ariel Flesler
|
841 |
-
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
|
842 |
-
*/
|
843 |
-
QUnit.jsDump = (function() {
|
844 |
-
function quote( str ) {
|
845 |
-
return '"' + str.toString().replace(/"/g, '\\"') + '"';
|
846 |
-
};
|
847 |
-
function literal( o ) {
|
848 |
-
return o + '';
|
849 |
-
};
|
850 |
-
function join( pre, arr, post ) {
|
851 |
-
var s = jsDump.separator(),
|
852 |
-
base = jsDump.indent(),
|
853 |
-
inner = jsDump.indent(1);
|
854 |
-
if ( arr.join )
|
855 |
-
arr = arr.join( ',' + s + inner );
|
856 |
-
if ( !arr )
|
857 |
-
return pre + post;
|
858 |
-
return [ pre, inner + arr, base + post ].join(s);
|
859 |
-
};
|
860 |
-
function array( arr ) {
|
861 |
-
var i = arr.length, ret = Array(i);
|
862 |
-
this.up();
|
863 |
-
while ( i-- )
|
864 |
-
ret[i] = this.parse( arr[i] );
|
865 |
-
this.down();
|
866 |
-
return join( '[', ret, ']' );
|
867 |
-
};
|
868 |
-
|
869 |
-
var reName = /^function (\w+)/;
|
870 |
-
|
871 |
-
var jsDump = {
|
872 |
-
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
|
873 |
-
var parser = this.parsers[ type || this.typeOf(obj) ];
|
874 |
-
type = typeof parser;
|
875 |
-
|
876 |
-
return type == 'function' ? parser.call( this, obj ) :
|
877 |
-
type == 'string' ? parser :
|
878 |
-
this.parsers.error;
|
879 |
-
},
|
880 |
-
typeOf:function( obj ) {
|
881 |
-
var type = typeof obj,
|
882 |
-
f = 'function';//we'll use it 3 times, save it
|
883 |
-
return type != 'object' && type != f ? type :
|
884 |
-
!obj ? 'null' :
|
885 |
-
obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions
|
886 |
-
obj.getHours ? 'date' :
|
887 |
-
obj.scrollBy ? 'window' :
|
888 |
-
obj.nodeName == '#document' ? 'document' :
|
889 |
-
obj.nodeName ? 'node' :
|
890 |
-
obj.item ? 'nodelist' : // Safari reports nodelists as functions
|
891 |
-
obj.callee ? 'arguments' :
|
892 |
-
obj.call || obj.constructor != Array && //an array would also fall on this hack
|
893 |
-
(obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects
|
894 |
-
'length' in obj ? 'array' :
|
895 |
-
type;
|
896 |
-
},
|
897 |
-
separator:function() {
|
898 |
-
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
|
899 |
-
},
|
900 |
-
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
|
901 |
-
if ( !this.multiline )
|
902 |
-
return '';
|
903 |
-
var chr = this.indentChar;
|
904 |
-
if ( this.HTML )
|
905 |
-
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
|
906 |
-
return Array( this._depth_ + (extra||0) ).join(chr);
|
907 |
-
},
|
908 |
-
up:function( a ) {
|
909 |
-
this._depth_ += a || 1;
|
910 |
-
},
|
911 |
-
down:function( a ) {
|
912 |
-
this._depth_ -= a || 1;
|
913 |
-
},
|
914 |
-
setParser:function( name, parser ) {
|
915 |
-
this.parsers[name] = parser;
|
916 |
-
},
|
917 |
-
// The next 3 are exposed so you can use them
|
918 |
-
quote:quote,
|
919 |
-
literal:literal,
|
920 |
-
join:join,
|
921 |
-
//
|
922 |
-
_depth_: 1,
|
923 |
-
// This is the list of parsers, to modify them, use jsDump.setParser
|
924 |
-
parsers:{
|
925 |
-
window: '[Window]',
|
926 |
-
document: '[Document]',
|
927 |
-
error:'[ERROR]', //when no parser is found, shouldn't happen
|
928 |
-
unknown: '[Unknown]',
|
929 |
-
'null':'null',
|
930 |
-
undefined:'undefined',
|
931 |
-
'function':function( fn ) {
|
932 |
-
var ret = 'function',
|
933 |
-
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
|
934 |
-
if ( name )
|
935 |
-
ret += ' ' + name;
|
936 |
-
ret += '(';
|
937 |
-
|
938 |
-
ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
|
939 |
-
return join( ret, this.parse(fn,'functionCode'), '}' );
|
940 |
-
},
|
941 |
-
array: array,
|
942 |
-
nodelist: array,
|
943 |
-
arguments: array,
|
944 |
-
object:function( map ) {
|
945 |
-
var ret = [ ];
|
946 |
-
this.up();
|
947 |
-
for ( var key in map )
|
948 |
-
ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
|
949 |
-
this.down();
|
950 |
-
return join( '{', ret, '}' );
|
951 |
-
},
|
952 |
-
node:function( node ) {
|
953 |
-
var open = this.HTML ? '<' : '<',
|
954 |
-
close = this.HTML ? '>' : '>';
|
955 |
-
|
956 |
-
var tag = node.nodeName.toLowerCase(),
|
957 |
-
ret = open + tag;
|
958 |
-
|
959 |
-
for ( var a in this.DOMAttrs ) {
|
960 |
-
var val = node[this.DOMAttrs[a]];
|
961 |
-
if ( val )
|
962 |
-
ret += ' ' + a + '=' + this.parse( val, 'attribute' );
|
963 |
-
}
|
964 |
-
return ret + close + open + '/' + tag + close;
|
965 |
-
},
|
966 |
-
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
|
967 |
-
var l = fn.length;
|
968 |
-
if ( !l ) return '';
|
969 |
-
|
970 |
-
var args = Array(l);
|
971 |
-
while ( l-- )
|
972 |
-
args[l] = String.fromCharCode(97+l);//97 is 'a'
|
973 |
-
return ' ' + args.join(', ') + ' ';
|
974 |
-
},
|
975 |
-
key:quote, //object calls it internally, the key part of an item in a map
|
976 |
-
functionCode:'[code]', //function calls it internally, it's the content of the function
|
977 |
-
attribute:quote, //node calls it internally, it's an html attribute value
|
978 |
-
string:quote,
|
979 |
-
date:quote,
|
980 |
-
regexp:literal, //regex
|
981 |
-
number:literal,
|
982 |
-
'boolean':literal
|
983 |
-
},
|
984 |
-
DOMAttrs:{//attributes to dump from nodes, name=>realName
|
985 |
-
id:'id',
|
986 |
-
name:'name',
|
987 |
-
'class':'className'
|
988 |
-
},
|
989 |
-
HTML:true,//if true, entities are escaped ( <, >, \t, space and \n )
|
990 |
-
indentChar:' ',//indentation unit
|
991 |
-
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
|
992 |
-
};
|
993 |
-
|
994 |
-
return jsDump;
|
995 |
-
})();
|
996 |
-
|
997 |
-
})(this);/*
|
998 |
-
* QUnit - A JavaScript Unit Testing Framework
|
999 |
-
*
|
1000 |
-
* http://docs.jquery.com/QUnit
|
1001 |
-
*
|
1002 |
-
* Copyright (c) 2009 John Resig, Jörn Zaefferer
|
1003 |
-
* Dual licensed under the MIT (MIT-LICENSE.txt)
|
1004 |
-
* and GPL (GPL-LICENSE.txt) licenses.
|
1005 |
-
*/
|
1006 |
-
|
1007 |
-
(function(window) {
|
1008 |
-
|
1009 |
-
var defined = {
|
1010 |
-
setTimeout: typeof window.setTimeout !== "undefined",
|
1011 |
-
sessionStorage: (function() {
|
1012 |
-
try {
|
1013 |
-
return !!sessionStorage.getItem;
|
1014 |
-
} catch(e){
|
1015 |
-
return false;
|
1016 |
-
}
|
1017 |
-
})()
|
1018 |
-
}
|
1019 |
-
|
1020 |
-
var testId = 0;
|
1021 |
-
|
1022 |
-
var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
|
1023 |
-
this.name = name;
|
1024 |
-
this.testName = testName;
|
1025 |
-
this.expected = expected;
|
1026 |
-
this.testEnvironmentArg = testEnvironmentArg;
|
1027 |
-
this.async = async;
|
1028 |
-
this.callback = callback;
|
1029 |
-
this.assertions = [];
|
1030 |
-
};
|
1031 |
-
Test.prototype = {
|
1032 |
-
init: function() {
|
1033 |
-
var tests = id("qunit-tests");
|
1034 |
-
if (tests) {
|
1035 |
-
var b = document.createElement("strong");
|
1036 |
-
b.innerHTML = "Running " + this.name;
|
1037 |
-
var li = document.createElement("li");
|
1038 |
-
li.appendChild( b );
|
1039 |
-
li.id = this.id = "test-output" + testId++;
|
1040 |
-
tests.appendChild( li );
|
1041 |
-
}
|
1042 |
-
},
|
1043 |
-
setup: function() {
|
1044 |
-
if (this.module != config.previousModule) {
|
1045 |
-
if ( this.previousModule ) {
|
1046 |
-
QUnit.moduleDone( this.module, config.moduleStats.bad, config.moduleStats.all );
|
1047 |
-
}
|
1048 |
-
config.previousModule = this.module;
|
1049 |
-
config.moduleStats = { all: 0, bad: 0 };
|
1050 |
-
QUnit.moduleStart( this.module, this.moduleTestEnvironment );
|
1051 |
-
}
|
1052 |
-
|
1053 |
-
config.current = this;
|
1054 |
-
this.testEnvironment = extend({
|
1055 |
-
setup: function() {},
|
1056 |
-
teardown: function() {}
|
1057 |
-
}, this.moduleTestEnvironment);
|
1058 |
-
if (this.testEnvironmentArg) {
|
1059 |
-
extend(this.testEnvironment, this.testEnvironmentArg);
|
1060 |
-
}
|
1061 |
-
|
1062 |
-
QUnit.testStart( this.testName, this.testEnvironment );
|
1063 |
-
|
1064 |
-
// allow utility functions to access the current test environment
|
1065 |
-
// TODO why??
|
1066 |
-
QUnit.current_testEnvironment = this.testEnvironment;
|
1067 |
-
|
1068 |
-
try {
|
1069 |
-
if ( !config.pollution ) {
|
1070 |
-
saveGlobal();
|
1071 |
-
}
|
1072 |
-
|
1073 |
-
this.testEnvironment.setup.call(this.testEnvironment);
|
1074 |
-
} catch(e) {
|
1075 |
-
// TODO use testName instead of name for no-markup message?
|
1076 |
-
QUnit.ok( false, "Setup failed on " + this.name + ": " + e.message );
|
1077 |
-
}
|
1078 |
-
},
|
1079 |
-
run: function() {
|
1080 |
-
if ( this.async ) {
|
1081 |
-
QUnit.stop();
|
1082 |
-
}
|
1083 |
-
|
1084 |
-
try {
|
1085 |
-
this.callback.call(this.testEnvironment);
|
1086 |
-
} catch(e) {
|
1087 |
-
// TODO use testName instead of name for no-markup message?
|
1088 |
-
fail("Test " + this.name + " died, exception and test follows", e, this.callback);
|
1089 |
-
QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
|
1090 |
-
// else next test will carry the responsibility
|
1091 |
-
saveGlobal();
|
1092 |
-
|
1093 |
-
// Restart the tests if they're blocking
|
1094 |
-
if ( config.blocking ) {
|
1095 |
-
start();
|
1096 |
-
}
|
1097 |
-
}
|
1098 |
-
},
|
1099 |
-
teardown: function() {
|
1100 |
-
try {
|
1101 |
-
checkPollution();
|
1102 |
-
this.testEnvironment.teardown.call(this.testEnvironment);
|
1103 |
-
} catch(e) {
|
1104 |
-
// TODO use testName instead of name for no-markup message?
|
1105 |
-
QUnit.ok( false, "Teardown failed on " + this.name + ": " + e.message );
|
1106 |
-
}
|
1107 |
-
},
|
1108 |
-
finish: function() {
|
1109 |
-
if ( this.expected && this.expected != this.assertions.length ) {
|
1110 |
-
QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
|
1111 |
-
}
|
1112 |
-
|
1113 |
-
var good = 0, bad = 0,
|
1114 |
-
tests = id("qunit-tests");
|
1115 |
-
|
1116 |
-
config.stats.all += this.assertions.length;
|
1117 |
-
config.moduleStats.all += this.assertions.length;
|
1118 |
-
|
1119 |
-
if ( tests ) {
|
1120 |
-
var ol = document.createElement("ol");
|
1121 |
-
|
1122 |
-
for ( var i = 0; i < this.assertions.length; i++ ) {
|
1123 |
-
var assertion = this.assertions[i];
|
1124 |
-
|
1125 |
-
var li = document.createElement("li");
|
1126 |
-
li.className = assertion.result ? "pass" : "fail";
|
1127 |
-
li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
|
1128 |
-
ol.appendChild( li );
|
1129 |
-
|
1130 |
-
if ( assertion.result ) {
|
1131 |
-
good++;
|
1132 |
-
} else {
|
1133 |
-
bad++;
|
1134 |
-
config.stats.bad++;
|
1135 |
-
config.moduleStats.bad++;
|
1136 |
-
}
|
1137 |
-
}
|
1138 |
-
|
1139 |
-
// store result when possible
|
1140 |
-
defined.sessionStorage && sessionStorage.setItem("qunit-" + this.testName, bad);
|
1141 |
-
|
1142 |
-
if (bad == 0) {
|
1143 |
-
ol.style.display = "none";
|
1144 |
-
}
|
1145 |
-
|
1146 |
-
var b = document.createElement("strong");
|
1147 |
-
b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
|
1148 |
-
|
1149 |
-
addEvent(b, "click", function() {
|
1150 |
-
var next = b.nextSibling, display = next.style.display;
|
1151 |
-
next.style.display = display === "none" ? "block" : "none";
|
1152 |
-
});
|
1153 |
-
|
1154 |
-
addEvent(b, "dblclick", function(e) {
|
1155 |
-
var target = e && e.target ? e.target : window.event.srcElement;
|
1156 |
-
if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
|
1157 |
-
target = target.parentNode;
|
1158 |
-
}
|
1159 |
-
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
|
1160 |
-
window.location.search = "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, ""));
|
1161 |
-
}
|
1162 |
-
});
|
1163 |
-
|
1164 |
-
var li = id(this.id);
|
1165 |
-
li.className = bad ? "fail" : "pass";
|
1166 |
-
li.style.display = resultDisplayStyle(!bad);
|
1167 |
-
li.removeChild( li.firstChild );
|
1168 |
-
li.appendChild( b );
|
1169 |
-
li.appendChild( ol );
|
1170 |
-
|
1171 |
-
if ( bad ) {
|
1172 |
-
var toolbar = id("qunit-testrunner-toolbar");
|
1173 |
-
if ( toolbar ) {
|
1174 |
-
toolbar.style.display = "block";
|
1175 |
-
id("qunit-filter-pass").disabled = null;
|
1176 |
-
}
|
1177 |
-
}
|
1178 |
-
|
1179 |
-
} else {
|
1180 |
-
for ( var i = 0; i < this.assertions.length; i++ ) {
|
1181 |
-
if ( !this.assertions[i].result ) {
|
1182 |
-
bad++;
|
1183 |
-
config.stats.bad++;
|
1184 |
-
config.moduleStats.bad++;
|
1185 |
-
}
|
1186 |
-
}
|
1187 |
-
}
|
1188 |
-
|
1189 |
-
try {
|
1190 |
-
QUnit.reset();
|
1191 |
-
} catch(e) {
|
1192 |
-
// TODO use testName instead of name for no-markup message?
|
1193 |
-
fail("reset() failed, following Test " + this.name + ", exception and reset fn follows", e, QUnit.reset);
|
1194 |
-
}
|
1195 |
-
|
1196 |
-
QUnit.testDone( this.testName, bad, this.assertions.length );
|
1197 |
-
},
|
1198 |
-
|
1199 |
-
queue: function() {
|
1200 |
-
var test = this;
|
1201 |
-
synchronize(function() {
|
1202 |
-
test.init();
|
1203 |
-
});
|
1204 |
-
function run() {
|
1205 |
-
// each of these can by async
|
1206 |
-
synchronize(function() {
|
1207 |
-
test.setup();
|
1208 |
-
});
|
1209 |
-
synchronize(function() {
|
1210 |
-
test.run();
|
1211 |
-
});
|
1212 |
-
synchronize(function() {
|
1213 |
-
test.teardown();
|
1214 |
-
});
|
1215 |
-
synchronize(function() {
|
1216 |
-
test.finish();
|
1217 |
-
});
|
1218 |
-
}
|
1219 |
-
// defer when previous test run passed, if storage is available
|
1220 |
-
var bad = defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.testName);
|
1221 |
-
if (bad) {
|
1222 |
-
run();
|
1223 |
-
} else {
|
1224 |
-
synchronize(run);
|
1225 |
-
};
|
1226 |
-
}
|
1227 |
-
|
1228 |
-
}
|
1229 |
-
|
1230 |
-
var QUnit = {
|
1231 |
-
|
1232 |
-
// call on start of module test to prepend name to all tests
|
1233 |
-
module: function(name, testEnvironment) {
|
1234 |
-
config.previousModule = config.currentModule;
|
1235 |
-
config.currentModule = name;
|
1236 |
-
config.currentModuleTestEnviroment = testEnvironment;
|
1237 |
-
},
|
1238 |
-
|
1239 |
-
asyncTest: function(testName, expected, callback) {
|
1240 |
-
if ( arguments.length === 2 ) {
|
1241 |
-
callback = expected;
|
1242 |
-
expected = 0;
|
1243 |
-
}
|
1244 |
-
|
1245 |
-
QUnit.test(testName, expected, callback, true);
|
1246 |
-
},
|
1247 |
-
|
1248 |
-
test: function(testName, expected, callback, async) {
|
1249 |
-
var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg;
|
1250 |
-
|
1251 |
-
if ( arguments.length === 2 ) {
|
1252 |
-
callback = expected;
|
1253 |
-
expected = null;
|
1254 |
-
}
|
1255 |
-
// is 2nd argument a testEnvironment?
|
1256 |
-
if ( expected && typeof expected === 'object') {
|
1257 |
-
testEnvironmentArg = expected;
|
1258 |
-
expected = null;
|
1259 |
-
}
|
1260 |
-
|
1261 |
-
if ( config.currentModule ) {
|
1262 |
-
name = '<span class="module-name">' + config.currentModule + "</span>: " + name;
|
1263 |
-
}
|
1264 |
-
|
1265 |
-
if ( !validTest(config.currentModule + ": " + testName) ) {
|
1266 |
-
return;
|
1267 |
-
}
|
1268 |
-
|
1269 |
-
var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
|
1270 |
-
test.previousModule = config.previousModule;
|
1271 |
-
test.module = config.currentModule;
|
1272 |
-
test.moduleTestEnvironment = config.currentModuleTestEnviroment;
|
1273 |
-
test.queue();
|
1274 |
-
},
|
1275 |
-
|
1276 |
-
/**
|
1277 |
-
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
|
1278 |
-
*/
|
1279 |
-
expect: function(asserts) {
|
1280 |
-
config.current.expected = asserts;
|
1281 |
-
},
|
1282 |
-
|
1283 |
-
/**
|
1284 |
-
* Asserts true.
|
1285 |
-
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
|
1286 |
-
*/
|
1287 |
-
ok: function(a, msg) {
|
1288 |
-
a = !!a;
|
1289 |
-
var details = {
|
1290 |
-
result: a,
|
1291 |
-
message: msg
|
1292 |
-
};
|
1293 |
-
msg = escapeHtml(msg);
|
1294 |
-
QUnit.log(a, msg, details);
|
1295 |
-
config.current.assertions.push({
|
1296 |
-
result: a,
|
1297 |
-
message: msg
|
1298 |
-
});
|
1299 |
-
},
|
1300 |
-
|
1301 |
-
/**
|
1302 |
-
* Checks that the first two arguments are equal, with an optional message.
|
1303 |
-
* Prints out both actual and expected values.
|
1304 |
-
*
|
1305 |
-
* Prefered to ok( actual == expected, message )
|
1306 |
-
*
|
1307 |
-
* @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
|
1308 |
-
*
|
1309 |
-
* @param Object actual
|
1310 |
-
* @param Object expected
|
1311 |
-
* @param String message (optional)
|
1312 |
-
*/
|
1313 |
-
equal: function(actual, expected, message) {
|
1314 |
-
QUnit.push(expected == actual, actual, expected, message);
|
1315 |
-
},
|
1316 |
-
|
1317 |
-
notEqual: function(actual, expected, message) {
|
1318 |
-
QUnit.push(expected != actual, actual, expected, message);
|
1319 |
-
},
|
1320 |
-
|
1321 |
-
deepEqual: function(actual, expected, message) {
|
1322 |
-
QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
|
1323 |
-
},
|
1324 |
-
|
1325 |
-
notDeepEqual: function(actual, expected, message) {
|
1326 |
-
QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
|
1327 |
-
},
|
1328 |
-
|
1329 |
-
strictEqual: function(actual, expected, message) {
|
1330 |
-
QUnit.push(expected === actual, actual, expected, message);
|
1331 |
-
},
|
1332 |
-
|
1333 |
-
notStrictEqual: function(actual, expected, message) {
|
1334 |
-
QUnit.push(expected !== actual, actual, expected, message);
|
1335 |
-
},
|
1336 |
-
|
1337 |
-
raises: function(block, expected, message) {
|
1338 |
-
var actual, ok = false;
|
1339 |
-
|
1340 |
-
if (typeof expected === 'string') {
|
1341 |
-
message = expected;
|
1342 |
-
expected = null;
|
1343 |
-
}
|
1344 |
-
|
1345 |
-
try {
|
1346 |
-
block();
|
1347 |
-
} catch (e) {
|
1348 |
-
actual = e;
|
1349 |
-
}
|
1350 |
-
|
1351 |
-
if (actual) {
|
1352 |
-
// we don't want to validate thrown error
|
1353 |
-
if (!expected) {
|
1354 |
-
ok = true;
|
1355 |
-
// expected is a regexp
|
1356 |
-
} else if (QUnit.objectType(expected) === "regexp") {
|
1357 |
-
ok = expected.test(actual);
|
1358 |
-
// expected is a constructor
|
1359 |
-
} else if (actual instanceof expected) {
|
1360 |
-
ok = true;
|
1361 |
-
// expected is a validation function which returns true is validation passed
|
1362 |
-
} else if (expected.call({}, actual) === true) {
|
1363 |
-
ok = true;
|
1364 |
-
}
|
1365 |
-
}
|
1366 |
-
|
1367 |
-
QUnit.ok(ok, message);
|
1368 |
-
},
|
1369 |
-
|
1370 |
-
start: function() {
|
1371 |
-
// A slight delay, to avoid any current callbacks
|
1372 |
-
if ( defined.setTimeout ) {
|
1373 |
-
window.setTimeout(function() {
|
1374 |
-
if ( config.timeout ) {
|
1375 |
-
clearTimeout(config.timeout);
|
1376 |
-
}
|
1377 |
-
|
1378 |
-
config.blocking = false;
|
1379 |
-
process();
|
1380 |
-
}, 13);
|
1381 |
-
} else {
|
1382 |
-
config.blocking = false;
|
1383 |
-
process();
|
1384 |
-
}
|
1385 |
-
},
|
1386 |
-
|
1387 |
-
stop: function(timeout) {
|
1388 |
-
config.blocking = true;
|
1389 |
-
|
1390 |
-
if ( timeout && defined.setTimeout ) {
|
1391 |
-
config.timeout = window.setTimeout(function() {
|
1392 |
-
QUnit.ok( false, "Test timed out" );
|
1393 |
-
QUnit.start();
|
1394 |
-
}, timeout);
|
1395 |
-
}
|
1396 |
-
}
|
1397 |
-
|
1398 |
-
};
|
1399 |
-
|
1400 |
-
// Backwards compatibility, deprecated
|
1401 |
-
QUnit.equals = QUnit.equal;
|
1402 |
-
QUnit.same = QUnit.deepEqual;
|
1403 |
-
|
1404 |
-
// Maintain internal state
|
1405 |
-
var config = {
|
1406 |
-
// The queue of tests to run
|
1407 |
-
queue: [],
|
1408 |
-
|
1409 |
-
// block until document ready
|
1410 |
-
blocking: true
|
1411 |
-
};
|
1412 |
-
|
1413 |
-
// Load paramaters
|
1414 |
-
(function() {
|
1415 |
-
var location = window.location || { search: "", protocol: "file:" },
|
1416 |
-
GETParams = location.search.slice(1).split('&');
|
1417 |
-
|
1418 |
-
for ( var i = 0; i < GETParams.length; i++ ) {
|
1419 |
-
GETParams[i] = decodeURIComponent( GETParams[i] );
|
1420 |
-
if ( GETParams[i] === "noglobals" ) {
|
1421 |
-
GETParams.splice( i, 1 );
|
1422 |
-
i--;
|
1423 |
-
config.noglobals = true;
|
1424 |
-
} else if ( GETParams[i].search('=') > -1 ) {
|
1425 |
-
GETParams.splice( i, 1 );
|
1426 |
-
i--;
|
1427 |
-
}
|
1428 |
-
}
|
1429 |
-
|
1430 |
-
// restrict modules/tests by get parameters
|
1431 |
-
config.filters = GETParams;
|
1432 |
-
|
1433 |
-
// Figure out if we're running the tests from a server or not
|
1434 |
-
QUnit.isLocal = !!(location.protocol === 'file:');
|
1435 |
-
})();
|
1436 |
-
|
1437 |
-
// Expose the API as global variables, unless an 'exports'
|
1438 |
-
// object exists, in that case we assume we're in CommonJS
|
1439 |
-
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
|
1440 |
-
extend(window, QUnit);
|
1441 |
-
window.QUnit = QUnit;
|
1442 |
-
} else {
|
1443 |
-
extend(exports, QUnit);
|
1444 |
-
exports.QUnit = QUnit;
|
1445 |
-
}
|
1446 |
-
|
1447 |
-
// define these after exposing globals to keep them in these QUnit namespace only
|
1448 |
-
extend(QUnit, {
|
1449 |
-
config: config,
|
1450 |
-
|
1451 |
-
// Initialize the configuration options
|
1452 |
-
init: function() {
|
1453 |
-
extend(config, {
|
1454 |
-
stats: { all: 0, bad: 0 },
|
1455 |
-
moduleStats: { all: 0, bad: 0 },
|
1456 |
-
started: +new Date,
|
1457 |
-
updateRate: 1000,
|
1458 |
-
blocking: false,
|
1459 |
-
autostart: true,
|
1460 |
-
autorun: false,
|
1461 |
-
filters: [],
|
1462 |
-
queue: []
|
1463 |
-
});
|
1464 |
-
|
1465 |
-
var tests = id("qunit-tests"),
|
1466 |
-
banner = id("qunit-banner"),
|
1467 |
-
result = id("qunit-testresult");
|
1468 |
-
|
1469 |
-
if ( tests ) {
|
1470 |
-
tests.innerHTML = "";
|
1471 |
-
}
|
1472 |
-
|
1473 |
-
if ( banner ) {
|
1474 |
-
banner.className = "";
|
1475 |
-
}
|
1476 |
-
|
1477 |
-
if ( result ) {
|
1478 |
-
result.parentNode.removeChild( result );
|
1479 |
-
}
|
1480 |
-
},
|
1481 |
-
|
1482 |
-
/**
|
1483 |
-
* Resets the test setup. Useful for tests that modify the DOM.
|
1484 |
-
*
|
1485 |
-
* If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
|
1486 |
-
*/
|
1487 |
-
reset: function() {
|
1488 |
-
if ( window.jQuery ) {
|
1489 |
-
jQuery( "#main, #qunit-fixture" ).html( config.fixture );
|
1490 |
-
} else {
|
1491 |
-
var main = id( 'main' ) || id( 'qunit-fixture' );
|
1492 |
-
if ( main ) {
|
1493 |
-
main.innerHTML = config.fixture;
|
1494 |
-
}
|
1495 |
-
}
|
1496 |
-
},
|
1497 |
-
|
1498 |
-
/**
|
1499 |
-
* Trigger an event on an element.
|
1500 |
-
*
|
1501 |
-
* @example triggerEvent( document.body, "click" );
|
1502 |
-
*
|
1503 |
-
* @param DOMElement elem
|
1504 |
-
* @param String type
|
1505 |
-
*/
|
1506 |
-
triggerEvent: function( elem, type, event ) {
|
1507 |
-
if ( document.createEvent ) {
|
1508 |
-
event = document.createEvent("MouseEvents");
|
1509 |
-
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
|
1510 |
-
0, 0, 0, 0, 0, false, false, false, false, 0, null);
|
1511 |
-
elem.dispatchEvent( event );
|
1512 |
-
|
1513 |
-
} else if ( elem.fireEvent ) {
|
1514 |
-
elem.fireEvent("on"+type);
|
1515 |
-
}
|
1516 |
-
},
|
1517 |
-
|
1518 |
-
// Safe object type checking
|
1519 |
-
is: function( type, obj ) {
|
1520 |
-
return QUnit.objectType( obj ) == type;
|
1521 |
-
},
|
1522 |
-
|
1523 |
-
objectType: function( obj ) {
|
1524 |
-
if (typeof obj === "undefined") {
|
1525 |
-
return "undefined";
|
1526 |
-
|
1527 |
-
// consider: typeof null === object
|
1528 |
-
}
|
1529 |
-
if (obj === null) {
|
1530 |
-
return "null";
|
1531 |
-
}
|
1532 |
-
|
1533 |
-
var type = Object.prototype.toString.call( obj )
|
1534 |
-
.match(/^\[object\s(.*)\]$/)[1] || '';
|
1535 |
-
|
1536 |
-
switch (type) {
|
1537 |
-
case 'Number':
|
1538 |
-
if (isNaN(obj)) {
|
1539 |
-
return "nan";
|
1540 |
-
} else {
|
1541 |
-
return "number";
|
1542 |
-
}
|
1543 |
-
case 'String':
|
1544 |
-
case 'Boolean':
|
1545 |
-
case 'Array':
|
1546 |
-
case 'Date':
|
1547 |
-
case 'RegExp':
|
1548 |
-
case 'Function':
|
1549 |
-
return type.toLowerCase();
|
1550 |
-
}
|
1551 |
-
if (typeof obj === "object") {
|
1552 |
-
return "object";
|
1553 |
-
}
|
1554 |
-
return undefined;
|
1555 |
-
},
|
1556 |
-
|
1557 |
-
push: function(result, actual, expected, message) {
|
1558 |
-
var details = {
|
1559 |
-
result: result,
|
1560 |
-
message: message,
|
1561 |
-
actual: actual,
|
1562 |
-
expected: expected
|
1563 |
-
};
|
1564 |
-
|
1565 |
-
message = escapeHtml(message) || (result ? "okay" : "failed");
|
1566 |
-
message = '<span class="test-message">' + message + "</span>";
|
1567 |
-
expected = escapeHtml(QUnit.jsDump.parse(expected));
|
1568 |
-
actual = escapeHtml(QUnit.jsDump.parse(actual));
|
1569 |
-
var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>';
|
1570 |
-
if (actual != expected) {
|
1571 |
-
output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>';
|
1572 |
-
output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>';
|
1573 |
-
}
|
1574 |
-
if (!result) {
|
1575 |
-
var source = sourceFromStacktrace();
|
1576 |
-
if (source) {
|
1577 |
-
details.source = source;
|
1578 |
-
output += '<tr class="test-source"><th>Source: </th><td><pre>' + source +'</pre></td></tr>';
|
1579 |
-
}
|
1580 |
-
}
|
1581 |
-
output += "</table>";
|
1582 |
-
|
1583 |
-
QUnit.log(result, message, details);
|
1584 |
-
|
1585 |
-
config.current.assertions.push({
|
1586 |
-
result: !!result,
|
1587 |
-
message: output
|
1588 |
-
});
|
1589 |
-
},
|
1590 |
-
|
1591 |
-
// Logging callbacks
|
1592 |
-
begin: function() {},
|
1593 |
-
done: function(failures, total) {},
|
1594 |
-
log: function(result, message) {},
|
1595 |
-
testStart: function(name, testEnvironment) {},
|
1596 |
-
testDone: function(name, failures, total) {},
|
1597 |
-
moduleStart: function(name, testEnvironment) {},
|
1598 |
-
moduleDone: function(name, failures, total) {}
|
1599 |
-
});
|
1600 |
-
|
1601 |
-
if ( typeof document === "undefined" || document.readyState === "complete" ) {
|
1602 |
-
config.autorun = true;
|
1603 |
-
}
|
1604 |
-
|
1605 |
-
addEvent(window, "load", function() {
|
1606 |
-
QUnit.begin();
|
1607 |
-
|
1608 |
-
// Initialize the config, saving the execution queue
|
1609 |
-
var oldconfig = extend({}, config);
|
1610 |
-
QUnit.init();
|
1611 |
-
extend(config, oldconfig);
|
1612 |
-
|
1613 |
-
config.blocking = false;
|
1614 |
-
|
1615 |
-
var userAgent = id("qunit-userAgent");
|
1616 |
-
if ( userAgent ) {
|
1617 |
-
userAgent.innerHTML = navigator.userAgent;
|
1618 |
-
}
|
1619 |
-
var banner = id("qunit-header");
|
1620 |
-
if ( banner ) {
|
1621 |
-
var paramsIndex = location.href.lastIndexOf(location.search);
|
1622 |
-
if ( paramsIndex > -1 ) {
|
1623 |
-
var mainPageLocation = location.href.slice(0, paramsIndex);
|
1624 |
-
if ( mainPageLocation == location.href ) {
|
1625 |
-
banner.innerHTML = '<a href=""> ' + banner.innerHTML + '</a> ';
|
1626 |
-
} else {
|
1627 |
-
var testName = decodeURIComponent(location.search.slice(1));
|
1628 |
-
|
1629 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
1630 |
-
// banner.innerHTML = '<a href="' + mainPageLocation + '">' + banner.innerHTML + '</a> › <a href="">' + testName + '</a>';
|
1631 |
-
// FIXED:
|
1632 |
-
|
1633 |
-
}
|
1634 |
-
}
|
1635 |
-
}
|
1636 |
-
|
1637 |
-
var toolbar = id("qunit-testrunner-toolbar");
|
1638 |
-
if ( toolbar ) {
|
1639 |
-
toolbar.style.display = "none";
|
1640 |
-
|
1641 |
-
var filter = document.createElement("input");
|
1642 |
-
filter.type = "checkbox";
|
1643 |
-
filter.id = "qunit-filter-pass";
|
1644 |
-
filter.disabled = true;
|
1645 |
-
addEvent( filter, "click", function() {
|
1646 |
-
var li = document.getElementsByTagName("li");
|
1647 |
-
for ( var i = 0; i < li.length; i++ ) {
|
1648 |
-
if ( li[i].className.indexOf("pass") > -1 ) {
|
1649 |
-
li[i].style.display = filter.checked ? "none" : "";
|
1650 |
-
}
|
1651 |
-
}
|
1652 |
-
});
|
1653 |
-
toolbar.appendChild( filter );
|
1654 |
-
|
1655 |
-
var label = document.createElement("label");
|
1656 |
-
label.setAttribute("for", "qunit-filter-pass");
|
1657 |
-
label.innerHTML = "Hide passed tests";
|
1658 |
-
toolbar.appendChild( label );
|
1659 |
-
}
|
1660 |
-
|
1661 |
-
var main = id('main') || id('qunit-fixture');
|
1662 |
-
if ( main ) {
|
1663 |
-
config.fixture = main.innerHTML;
|
1664 |
-
}
|
1665 |
-
|
1666 |
-
if (config.autostart) {
|
1667 |
-
QUnit.start();
|
1668 |
-
}
|
1669 |
-
});
|
1670 |
-
|
1671 |
-
function done() {
|
1672 |
-
config.autorun = true;
|
1673 |
-
|
1674 |
-
// Log the last module results
|
1675 |
-
if ( config.currentModule ) {
|
1676 |
-
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
|
1677 |
-
}
|
1678 |
-
|
1679 |
-
var banner = id("qunit-banner"),
|
1680 |
-
tests = id("qunit-tests"),
|
1681 |
-
html = ['Tests completed in ',
|
1682 |
-
+new Date - config.started, ' milliseconds.<br/>',
|
1683 |
-
'<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('');
|
1684 |
-
|
1685 |
-
if ( banner ) {
|
1686 |
-
banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
|
1687 |
-
}
|
1688 |
-
|
1689 |
-
if ( tests ) {
|
1690 |
-
var result = id("qunit-testresult");
|
1691 |
-
|
1692 |
-
if ( !result ) {
|
1693 |
-
result = document.createElement("p");
|
1694 |
-
result.id = "qunit-testresult";
|
1695 |
-
result.className = "result";
|
1696 |
-
tests.parentNode.insertBefore( result, tests.nextSibling );
|
1697 |
-
}
|
1698 |
-
|
1699 |
-
result.innerHTML = html;
|
1700 |
-
}
|
1701 |
-
|
1702 |
-
QUnit.done( config.stats.bad, config.stats.all );
|
1703 |
-
}
|
1704 |
-
|
1705 |
-
function validTest( name ) {
|
1706 |
-
var i = config.filters.length,
|
1707 |
-
run = false;
|
1708 |
-
|
1709 |
-
if ( !i ) {
|
1710 |
-
return true;
|
1711 |
-
}
|
1712 |
-
|
1713 |
-
while ( i-- ) {
|
1714 |
-
var filter = config.filters[i],
|
1715 |
-
not = filter.charAt(0) == '!';
|
1716 |
-
|
1717 |
-
if ( not ) {
|
1718 |
-
filter = filter.slice(1);
|
1719 |
-
}
|
1720 |
-
|
1721 |
-
if ( name.indexOf(filter) !== -1 ) {
|
1722 |
-
return !not;
|
1723 |
-
}
|
1724 |
-
|
1725 |
-
if ( not ) {
|
1726 |
-
run = true;
|
1727 |
-
}
|
1728 |
-
}
|
1729 |
-
|
1730 |
-
return run;
|
1731 |
-
}
|
1732 |
-
|
1733 |
-
// so far supports only Firefox, Chrome and Opera (buggy)
|
1734 |
-
// could be extended in the future to use something like https://github.com/csnover/TraceKit
|
1735 |
-
function sourceFromStacktrace() {
|
1736 |
-
try {
|
1737 |
-
throw new Error();
|
1738 |
-
} catch ( e ) {
|
1739 |
-
if (e.stacktrace) {
|
1740 |
-
// Opera
|
1741 |
-
return e.stacktrace.split("\n")[6];
|
1742 |
-
} else if (e.stack) {
|
1743 |
-
// Firefox, Chrome
|
1744 |
-
return e.stack.split("\n")[4];
|
1745 |
-
}
|
1746 |
-
}
|
1747 |
-
}
|
1748 |
-
|
1749 |
-
function resultDisplayStyle(passed) {
|
1750 |
-
return passed && id("qunit-filter-pass") && id("qunit-filter-pass").checked ? 'none' : '';
|
1751 |
-
}
|
1752 |
-
|
1753 |
-
function escapeHtml(s) {
|
1754 |
-
if (!s) {
|
1755 |
-
return "";
|
1756 |
-
}
|
1757 |
-
s = s + "";
|
1758 |
-
return s.replace(/[\&"<>\\]/g, function(s) {
|
1759 |
-
switch(s) {
|
1760 |
-
case "&": return "&";
|
1761 |
-
case "\\": return "\\\\";
|
1762 |
-
case '"': return '\"';
|
1763 |
-
case "<": return "<";
|
1764 |
-
case ">": return ">";
|
1765 |
-
default: return s;
|
1766 |
-
}
|
1767 |
-
});
|
1768 |
-
}
|
1769 |
-
|
1770 |
-
function synchronize( callback ) {
|
1771 |
-
config.queue.push( callback );
|
1772 |
-
|
1773 |
-
if ( config.autorun && !config.blocking ) {
|
1774 |
-
process();
|
1775 |
-
}
|
1776 |
-
}
|
1777 |
-
|
1778 |
-
function process() {
|
1779 |
-
var start = (new Date()).getTime();
|
1780 |
-
|
1781 |
-
while ( config.queue.length && !config.blocking ) {
|
1782 |
-
if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
|
1783 |
-
config.queue.shift()();
|
1784 |
-
} else {
|
1785 |
-
window.setTimeout( process, 13 );
|
1786 |
-
break;
|
1787 |
-
}
|
1788 |
-
}
|
1789 |
-
if (!config.blocking && !config.queue.length) {
|
1790 |
-
done();
|
1791 |
-
}
|
1792 |
-
}
|
1793 |
-
|
1794 |
-
function saveGlobal() {
|
1795 |
-
config.pollution = [];
|
1796 |
-
|
1797 |
-
if ( config.noglobals ) {
|
1798 |
-
for ( var key in window ) {
|
1799 |
-
config.pollution.push( key );
|
1800 |
-
}
|
1801 |
-
}
|
1802 |
-
}
|
1803 |
-
|
1804 |
-
function checkPollution( name ) {
|
1805 |
-
var old = config.pollution;
|
1806 |
-
saveGlobal();
|
1807 |
-
|
1808 |
-
var newGlobals = diff( old, config.pollution );
|
1809 |
-
if ( newGlobals.length > 0 ) {
|
1810 |
-
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
|
1811 |
-
config.current.expected++;
|
1812 |
-
}
|
1813 |
-
|
1814 |
-
var deletedGlobals = diff( config.pollution, old );
|
1815 |
-
if ( deletedGlobals.length > 0 ) {
|
1816 |
-
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
|
1817 |
-
config.current.expected++;
|
1818 |
-
}
|
1819 |
-
}
|
1820 |
-
|
1821 |
-
// returns a new Array with the elements that are in a but not in b
|
1822 |
-
function diff( a, b ) {
|
1823 |
-
var result = a.slice();
|
1824 |
-
for ( var i = 0; i < result.length; i++ ) {
|
1825 |
-
for ( var j = 0; j < b.length; j++ ) {
|
1826 |
-
if ( result[i] === b[j] ) {
|
1827 |
-
result.splice(i, 1);
|
1828 |
-
i--;
|
1829 |
-
break;
|
1830 |
-
}
|
1831 |
-
}
|
1832 |
-
}
|
1833 |
-
return result;
|
1834 |
-
}
|
1835 |
-
|
1836 |
-
function fail(message, exception, callback) {
|
1837 |
-
if ( typeof console !== "undefined" && console.error && console.warn ) {
|
1838 |
-
console.error(message);
|
1839 |
-
console.error(exception);
|
1840 |
-
console.warn(callback.toString());
|
1841 |
-
|
1842 |
-
} else if ( window.opera && opera.postError ) {
|
1843 |
-
opera.postError(message, exception, callback.toString);
|
1844 |
-
}
|
1845 |
-
}
|
1846 |
-
|
1847 |
-
function extend(a, b) {
|
1848 |
-
for ( var prop in b ) {
|
1849 |
-
a[prop] = b[prop];
|
1850 |
-
}
|
1851 |
-
|
1852 |
-
return a;
|
1853 |
-
}
|
1854 |
-
|
1855 |
-
function addEvent(elem, type, fn) {
|
1856 |
-
if ( elem.addEventListener ) {
|
1857 |
-
elem.addEventListener( type, fn, false );
|
1858 |
-
} else if ( elem.attachEvent ) {
|
1859 |
-
elem.attachEvent( "on" + type, fn );
|
1860 |
-
} else {
|
1861 |
-
fn();
|
1862 |
-
}
|
1863 |
-
}
|
1864 |
-
|
1865 |
-
function id(name) {
|
1866 |
-
return !!(typeof document !== "undefined" && document && document.getElementById) &&
|
1867 |
-
document.getElementById( name );
|
1868 |
-
}
|
1869 |
-
|
1870 |
-
// Test for equality any JavaScript type.
|
1871 |
-
// Discussions and reference: http://philrathe.com/articles/equiv
|
1872 |
-
// Test suites: http://philrathe.com/tests/equiv
|
1873 |
-
// Author: Philippe Rathé <prathe@gmail.com>
|
1874 |
-
QUnit.equiv = function () {
|
1875 |
-
|
1876 |
-
var innerEquiv; // the real equiv function
|
1877 |
-
var callers = []; // stack to decide between skip/abort functions
|
1878 |
-
var parents = []; // stack to avoiding loops from circular referencing
|
1879 |
-
|
1880 |
-
// Call the o related callback with the given arguments.
|
1881 |
-
function bindCallbacks(o, callbacks, args) {
|
1882 |
-
var prop = QUnit.objectType(o);
|
1883 |
-
if (prop) {
|
1884 |
-
if (QUnit.objectType(callbacks[prop]) === "function") {
|
1885 |
-
return callbacks[prop].apply(callbacks, args);
|
1886 |
-
} else {
|
1887 |
-
return callbacks[prop]; // or undefined
|
1888 |
-
}
|
1889 |
-
}
|
1890 |
-
}
|
1891 |
-
|
1892 |
-
var callbacks = function () {
|
1893 |
-
|
1894 |
-
// for string, boolean, number and null
|
1895 |
-
function useStrictEquality(b, a) {
|
1896 |
-
if (b instanceof a.constructor || a instanceof b.constructor) {
|
1897 |
-
// to catch short annotaion VS 'new' annotation of a declaration
|
1898 |
-
// e.g. var i = 1;
|
1899 |
-
// var j = new Number(1);
|
1900 |
-
return a == b;
|
1901 |
-
} else {
|
1902 |
-
return a === b;
|
1903 |
-
}
|
1904 |
-
}
|
1905 |
-
|
1906 |
-
return {
|
1907 |
-
"string": useStrictEquality,
|
1908 |
-
"boolean": useStrictEquality,
|
1909 |
-
"number": useStrictEquality,
|
1910 |
-
"null": useStrictEquality,
|
1911 |
-
"undefined": useStrictEquality,
|
1912 |
-
|
1913 |
-
"nan": function (b) {
|
1914 |
-
return isNaN(b);
|
1915 |
-
},
|
1916 |
-
|
1917 |
-
"date": function (b, a) {
|
1918 |
-
return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf();
|
1919 |
-
},
|
1920 |
-
|
1921 |
-
"regexp": function (b, a) {
|
1922 |
-
return QUnit.objectType(b) === "regexp" &&
|
1923 |
-
a.source === b.source && // the regex itself
|
1924 |
-
a.global === b.global && // and its modifers (gmi) ...
|
1925 |
-
a.ignoreCase === b.ignoreCase &&
|
1926 |
-
a.multiline === b.multiline;
|
1927 |
-
},
|
1928 |
-
|
1929 |
-
// - skip when the property is a method of an instance (OOP)
|
1930 |
-
// - abort otherwise,
|
1931 |
-
// initial === would have catch identical references anyway
|
1932 |
-
"function": function () {
|
1933 |
-
var caller = callers[callers.length - 1];
|
1934 |
-
return caller !== Object &&
|
1935 |
-
typeof caller !== "undefined";
|
1936 |
-
},
|
1937 |
-
|
1938 |
-
"array": function (b, a) {
|
1939 |
-
var i, j, loop;
|
1940 |
-
var len;
|
1941 |
-
|
1942 |
-
// b could be an object literal here
|
1943 |
-
if ( ! (QUnit.objectType(b) === "array")) {
|
1944 |
-
return false;
|
1945 |
-
}
|
1946 |
-
|
1947 |
-
len = a.length;
|
1948 |
-
if (len !== b.length) { // safe and faster
|
1949 |
-
return false;
|
1950 |
-
}
|
1951 |
-
|
1952 |
-
//track reference to avoid circular references
|
1953 |
-
parents.push(a);
|
1954 |
-
for (i = 0; i < len; i++) {
|
1955 |
-
loop = false;
|
1956 |
-
for(j=0;j<parents.length;j++){
|
1957 |
-
if(parents[j] === a[i]){
|
1958 |
-
loop = true;//dont rewalk array
|
1959 |
-
}
|
1960 |
-
}
|
1961 |
-
if (!loop && ! innerEquiv(a[i], b[i])) {
|
1962 |
-
parents.pop();
|
1963 |
-
return false;
|
1964 |
-
}
|
1965 |
-
}
|
1966 |
-
parents.pop();
|
1967 |
-
return true;
|
1968 |
-
},
|
1969 |
-
|
1970 |
-
"object": function (b, a) {
|
1971 |
-
var i, j, loop;
|
1972 |
-
var eq = true; // unless we can proove it
|
1973 |
-
var aProperties = [], bProperties = []; // collection of strings
|
1974 |
-
|
1975 |
-
// comparing constructors is more strict than using instanceof
|
1976 |
-
if ( a.constructor !== b.constructor) {
|
1977 |
-
return false;
|
1978 |
-
}
|
1979 |
-
|
1980 |
-
// stack constructor before traversing properties
|
1981 |
-
callers.push(a.constructor);
|
1982 |
-
//track reference to avoid circular references
|
1983 |
-
parents.push(a);
|
1984 |
-
|
1985 |
-
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
|
1986 |
-
loop = false;
|
1987 |
-
for(j=0;j<parents.length;j++){
|
1988 |
-
if(parents[j] === a[i])
|
1989 |
-
loop = true; //don't go down the same path twice
|
1990 |
-
}
|
1991 |
-
aProperties.push(i); // collect a's properties
|
1992 |
-
|
1993 |
-
if (!loop && ! innerEquiv(a[i], b[i])) {
|
1994 |
-
eq = false;
|
1995 |
-
break;
|
1996 |
-
}
|
1997 |
-
}
|
1998 |
-
|
1999 |
-
callers.pop(); // unstack, we are done
|
2000 |
-
parents.pop();
|
2001 |
-
|
2002 |
-
for (i in b) {
|
2003 |
-
bProperties.push(i); // collect b's properties
|
2004 |
-
}
|
2005 |
-
|
2006 |
-
// Ensures identical properties name
|
2007 |
-
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
|
2008 |
-
}
|
2009 |
-
};
|
2010 |
-
}();
|
2011 |
-
|
2012 |
-
innerEquiv = function () { // can take multiple arguments
|
2013 |
-
var args = Array.prototype.slice.apply(arguments);
|
2014 |
-
if (args.length < 2) {
|
2015 |
-
return true; // end transition
|
2016 |
-
}
|
2017 |
-
|
2018 |
-
return (function (a, b) {
|
2019 |
-
if (a === b) {
|
2020 |
-
return true; // catch the most you can
|
2021 |
-
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) {
|
2022 |
-
return false; // don't lose time with error prone cases
|
2023 |
-
} else {
|
2024 |
-
return bindCallbacks(a, callbacks, [b, a]);
|
2025 |
-
}
|
2026 |
-
|
2027 |
-
// apply transition with (1..n) arguments
|
2028 |
-
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
|
2029 |
-
};
|
2030 |
-
|
2031 |
-
return innerEquiv;
|
2032 |
-
|
2033 |
-
}();
|
2034 |
-
|
2035 |
-
/**
|
2036 |
-
* jsDump
|
2037 |
-
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
|
2038 |
-
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
|
2039 |
-
* Date: 5/15/2008
|
2040 |
-
* @projectDescription Advanced and extensible data dumping for Javascript.
|
2041 |
-
* @version 1.0.0
|
2042 |
-
* @author Ariel Flesler
|
2043 |
-
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
|
2044 |
-
*/
|
2045 |
-
QUnit.jsDump = (function() {
|
2046 |
-
function quote( str ) {
|
2047 |
-
return '"' + str.toString().replace(/"/g, '\\"') + '"';
|
2048 |
-
};
|
2049 |
-
function literal( o ) {
|
2050 |
-
return o + '';
|
2051 |
-
};
|
2052 |
-
function join( pre, arr, post ) {
|
2053 |
-
var s = jsDump.separator(),
|
2054 |
-
base = jsDump.indent(),
|
2055 |
-
inner = jsDump.indent(1);
|
2056 |
-
if ( arr.join )
|
2057 |
-
arr = arr.join( ',' + s + inner );
|
2058 |
-
if ( !arr )
|
2059 |
-
return pre + post;
|
2060 |
-
return [ pre, inner + arr, base + post ].join(s);
|
2061 |
-
};
|
2062 |
-
function array( arr ) {
|
2063 |
-
var i = arr.length, ret = Array(i);
|
2064 |
-
this.up();
|
2065 |
-
while ( i-- )
|
2066 |
-
ret[i] = this.parse( arr[i] );
|
2067 |
-
this.down();
|
2068 |
-
return join( '[', ret, ']' );
|
2069 |
-
};
|
2070 |
-
|
2071 |
-
var reName = /^function (\w+)/;
|
2072 |
-
|
2073 |
-
var jsDump = {
|
2074 |
-
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
|
2075 |
-
var parser = this.parsers[ type || this.typeOf(obj) ];
|
2076 |
-
type = typeof parser;
|
2077 |
-
|
2078 |
-
return type == 'function' ? parser.call( this, obj ) :
|
2079 |
-
type == 'string' ? parser :
|
2080 |
-
this.parsers.error;
|
2081 |
-
},
|
2082 |
-
typeOf:function( obj ) {
|
2083 |
-
var type;
|
2084 |
-
if ( obj === null ) {
|
2085 |
-
type = "null";
|
2086 |
-
} else if (typeof obj === "undefined") {
|
2087 |
-
type = "undefined";
|
2088 |
-
} else if (QUnit.is("RegExp", obj)) {
|
2089 |
-
type = "regexp";
|
2090 |
-
} else if (QUnit.is("Date", obj)) {
|
2091 |
-
type = "date";
|
2092 |
-
} else if (QUnit.is("Function", obj)) {
|
2093 |
-
type = "function";
|
2094 |
-
} else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
|
2095 |
-
type = "window";
|
2096 |
-
} else if (obj.nodeType === 9) {
|
2097 |
-
type = "document";
|
2098 |
-
} else if (obj.nodeType) {
|
2099 |
-
type = "node";
|
2100 |
-
} else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
|
2101 |
-
type = "array";
|
2102 |
-
} else {
|
2103 |
-
type = typeof obj;
|
2104 |
-
}
|
2105 |
-
return type;
|
2106 |
-
},
|
2107 |
-
separator:function() {
|
2108 |
-
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
|
2109 |
-
},
|
2110 |
-
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
|
2111 |
-
if ( !this.multiline )
|
2112 |
-
return '';
|
2113 |
-
var chr = this.indentChar;
|
2114 |
-
if ( this.HTML )
|
2115 |
-
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
|
2116 |
-
return Array( this._depth_ + (extra||0) ).join(chr);
|
2117 |
-
},
|
2118 |
-
up:function( a ) {
|
2119 |
-
this._depth_ += a || 1;
|
2120 |
-
},
|
2121 |
-
down:function( a ) {
|
2122 |
-
this._depth_ -= a || 1;
|
2123 |
-
},
|
2124 |
-
setParser:function( name, parser ) {
|
2125 |
-
this.parsers[name] = parser;
|
2126 |
-
},
|
2127 |
-
// The next 3 are exposed so you can use them
|
2128 |
-
quote:quote,
|
2129 |
-
literal:literal,
|
2130 |
-
join:join,
|
2131 |
-
//
|
2132 |
-
_depth_: 1,
|
2133 |
-
// This is the list of parsers, to modify them, use jsDump.setParser
|
2134 |
-
parsers:{
|
2135 |
-
window: '[Window]',
|
2136 |
-
document: '[Document]',
|
2137 |
-
error:'[ERROR]', //when no parser is found, shouldn't happen
|
2138 |
-
unknown: '[Unknown]',
|
2139 |
-
'null':'null',
|
2140 |
-
undefined:'undefined',
|
2141 |
-
'function':function( fn ) {
|
2142 |
-
var ret = 'function',
|
2143 |
-
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
|
2144 |
-
if ( name )
|
2145 |
-
ret += ' ' + name;
|
2146 |
-
ret += '(';
|
2147 |
-
|
2148 |
-
ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
|
2149 |
-
return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
|
2150 |
-
},
|
2151 |
-
array: array,
|
2152 |
-
nodelist: array,
|
2153 |
-
arguments: array,
|
2154 |
-
object:function( map ) {
|
2155 |
-
var ret = [ ];
|
2156 |
-
QUnit.jsDump.up();
|
2157 |
-
for ( var key in map )
|
2158 |
-
ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) );
|
2159 |
-
QUnit.jsDump.down();
|
2160 |
-
return join( '{', ret, '}' );
|
2161 |
-
},
|
2162 |
-
node:function( node ) {
|
2163 |
-
var open = QUnit.jsDump.HTML ? '<' : '<',
|
2164 |
-
close = QUnit.jsDump.HTML ? '>' : '>';
|
2165 |
-
|
2166 |
-
var tag = node.nodeName.toLowerCase(),
|
2167 |
-
ret = open + tag;
|
2168 |
-
|
2169 |
-
for ( var a in QUnit.jsDump.DOMAttrs ) {
|
2170 |
-
var val = node[QUnit.jsDump.DOMAttrs[a]];
|
2171 |
-
if ( val )
|
2172 |
-
ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
|
2173 |
-
}
|
2174 |
-
return ret + close + open + '/' + tag + close;
|
2175 |
-
},
|
2176 |
-
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
|
2177 |
-
var l = fn.length;
|
2178 |
-
if ( !l ) return '';
|
2179 |
-
|
2180 |
-
var args = Array(l);
|
2181 |
-
while ( l-- )
|
2182 |
-
args[l] = String.fromCharCode(97+l);//97 is 'a'
|
2183 |
-
return ' ' + args.join(', ') + ' ';
|
2184 |
-
},
|
2185 |
-
key:quote, //object calls it internally, the key part of an item in a map
|
2186 |
-
functionCode:'[code]', //function calls it internally, it's the content of the function
|
2187 |
-
attribute:quote, //node calls it internally, it's an html attribute value
|
2188 |
-
string:quote,
|
2189 |
-
date:quote,
|
2190 |
-
regexp:literal, //regex
|
2191 |
-
number:literal,
|
2192 |
-
'boolean':literal
|
2193 |
-
},
|
2194 |
-
DOMAttrs:{//attributes to dump from nodes, name=>realName
|
2195 |
-
id:'id',
|
2196 |
-
name:'name',
|
2197 |
-
'class':'className'
|
2198 |
-
},
|
2199 |
-
HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
|
2200 |
-
indentChar:' ',//indentation unit
|
2201 |
-
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
|
2202 |
-
};
|
2203 |
-
|
2204 |
-
return jsDump;
|
2205 |
-
})();
|
2206 |
-
|
2207 |
-
// from Sizzle.js
|
2208 |
-
function getText( elems ) {
|
2209 |
-
var ret = "", elem;
|
2210 |
-
|
2211 |
-
for ( var i = 0; elems[i]; i++ ) {
|
2212 |
-
elem = elems[i];
|
2213 |
-
|
2214 |
-
// Get the text from text nodes and CDATA nodes
|
2215 |
-
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
|
2216 |
-
ret += elem.nodeValue;
|
2217 |
-
|
2218 |
-
// Traverse everything else, except comment nodes
|
2219 |
-
} else if ( elem.nodeType !== 8 ) {
|
2220 |
-
ret += getText( elem.childNodes );
|
2221 |
-
}
|
2222 |
-
}
|
2223 |
-
|
2224 |
-
return ret;
|
2225 |
-
};
|
2226 |
-
|
2227 |
-
/*
|
2228 |
-
* Javascript Diff Algorithm
|
2229 |
-
* By John Resig (http://ejohn.org/)
|
2230 |
-
* Modified by Chu Alan "sprite"
|
2231 |
-
*
|
2232 |
-
* Released under the MIT license.
|
2233 |
-
*
|
2234 |
-
* More Info:
|
2235 |
-
* http://ejohn.org/projects/javascript-diff-algorithm/
|
2236 |
-
*
|
2237 |
-
* Usage: QUnit.diff(expected, actual)
|
2238 |
-
*
|
2239 |
-
* 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"
|
2240 |
-
*/
|
2241 |
-
QUnit.diff = (function() {
|
2242 |
-
function diff(o, n){
|
2243 |
-
var ns = new Object();
|
2244 |
-
var os = new Object();
|
2245 |
-
|
2246 |
-
for (var i = 0; i < n.length; i++) {
|
2247 |
-
if (ns[n[i]] == null)
|
2248 |
-
ns[n[i]] = {
|
2249 |
-
rows: new Array(),
|
2250 |
-
o: null
|
2251 |
-
};
|
2252 |
-
ns[n[i]].rows.push(i);
|
2253 |
-
}
|
2254 |
-
|
2255 |
-
for (var i = 0; i < o.length; i++) {
|
2256 |
-
if (os[o[i]] == null)
|
2257 |
-
os[o[i]] = {
|
2258 |
-
rows: new Array(),
|
2259 |
-
n: null
|
2260 |
-
};
|
2261 |
-
os[o[i]].rows.push(i);
|
2262 |
-
}
|
2263 |
-
|
2264 |
-
for (var i in ns) {
|
2265 |
-
if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
|
2266 |
-
n[ns[i].rows[0]] = {
|
2267 |
-
text: n[ns[i].rows[0]],
|
2268 |
-
row: os[i].rows[0]
|
2269 |
-
};
|
2270 |
-
o[os[i].rows[0]] = {
|
2271 |
-
text: o[os[i].rows[0]],
|
2272 |
-
row: ns[i].rows[0]
|
2273 |
-
};
|
2274 |
-
}
|
2275 |
-
}
|
2276 |
-
|
2277 |
-
for (var i = 0; i < n.length - 1; i++) {
|
2278 |
-
if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
|
2279 |
-
n[i + 1] == o[n[i].row + 1]) {
|
2280 |
-
n[i + 1] = {
|
2281 |
-
text: n[i + 1],
|
2282 |
-
row: n[i].row + 1
|
2283 |
-
};
|
2284 |
-
o[n[i].row + 1] = {
|
2285 |
-
text: o[n[i].row + 1],
|
2286 |
-
row: i + 1
|
2287 |
-
};
|
2288 |
-
}
|
2289 |
-
}
|
2290 |
-
|
2291 |
-
for (var i = n.length - 1; i > 0; i--) {
|
2292 |
-
if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
|
2293 |
-
n[i - 1] == o[n[i].row - 1]) {
|
2294 |
-
n[i - 1] = {
|
2295 |
-
text: n[i - 1],
|
2296 |
-
row: n[i].row - 1
|
2297 |
-
};
|
2298 |
-
o[n[i].row - 1] = {
|
2299 |
-
text: o[n[i].row - 1],
|
2300 |
-
row: i - 1
|
2301 |
-
};
|
2302 |
-
}
|
2303 |
-
}
|
2304 |
-
|
2305 |
-
return {
|
2306 |
-
o: o,
|
2307 |
-
n: n
|
2308 |
-
};
|
2309 |
-
}
|
2310 |
-
|
2311 |
-
return function(o, n){
|
2312 |
-
o = o.replace(/\s+$/, '');
|
2313 |
-
n = n.replace(/\s+$/, '');
|
2314 |
-
var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
|
2315 |
-
|
2316 |
-
var str = "";
|
2317 |
-
|
2318 |
-
var oSpace = o.match(/\s+/g);
|
2319 |
-
if (oSpace == null) {
|
2320 |
-
oSpace = [" "];
|
2321 |
-
}
|
2322 |
-
else {
|
2323 |
-
oSpace.push(" ");
|
2324 |
-
}
|
2325 |
-
var nSpace = n.match(/\s+/g);
|
2326 |
-
if (nSpace == null) {
|
2327 |
-
nSpace = [" "];
|
2328 |
-
}
|
2329 |
-
else {
|
2330 |
-
nSpace.push(" ");
|
2331 |
-
}
|
2332 |
-
|
2333 |
-
if (out.n.length == 0) {
|
2334 |
-
for (var i = 0; i < out.o.length; i++) {
|
2335 |
-
str += '<del>' + out.o[i] + oSpace[i] + "</del>";
|
2336 |
-
}
|
2337 |
-
}
|
2338 |
-
else {
|
2339 |
-
if (out.n[0].text == null) {
|
2340 |
-
for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
|
2341 |
-
str += '<del>' + out.o[n] + oSpace[n] + "</del>";
|
2342 |
-
}
|
2343 |
-
}
|
2344 |
-
|
2345 |
-
for (var i = 0; i < out.n.length; i++) {
|
2346 |
-
if (out.n[i].text == null) {
|
2347 |
-
str += '<ins>' + out.n[i] + nSpace[i] + "</ins>";
|
2348 |
-
}
|
2349 |
-
else {
|
2350 |
-
var pre = "";
|
2351 |
-
|
2352 |
-
for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
|
2353 |
-
pre += '<del>' + out.o[n] + oSpace[n] + "</del>";
|
2354 |
-
}
|
2355 |
-
str += " " + out.n[i].text + nSpace[i] + pre;
|
2356 |
-
}
|
2357 |
-
}
|
2358 |
-
}
|
2359 |
-
|
2360 |
-
return str;
|
2361 |
-
};
|
2362 |
-
})();
|
2363 |
-
|
2364 |
-
})(this);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/126.js
DELETED
@@ -1,2086 +0,0 @@
|
|
1 |
-
define("dijit/_editor/RichText", ["dojo", "dijit", "dijit/_Widget", "dijit/_CssStateMixin", "dijit/_editor/selection", "dijit/_editor/range", "dijit/_editor/html"], function(dojo, dijit) {
|
2 |
-
|
3 |
-
// used to restore content when user leaves this page then comes back
|
4 |
-
// but do not try doing dojo.doc.write if we are using xd loading.
|
5 |
-
// dojo.doc.write will only work if RichText.js is included in the dojo.js
|
6 |
-
// file. If it is included in dojo.js and you want to allow rich text saving
|
7 |
-
// for back/forward actions, then set dojo.config.allowXdRichTextSave = true.
|
8 |
-
if(!dojo.config["useXDomain"] || dojo.config["allowXdRichTextSave"]){
|
9 |
-
if(dojo._postLoad){
|
10 |
-
(function(){
|
11 |
-
var savetextarea = dojo.doc.createElement('textarea');
|
12 |
-
savetextarea.id = dijit._scopeName + "._editor.RichText.value";
|
13 |
-
dojo.style(savetextarea, {
|
14 |
-
display:'none',
|
15 |
-
position:'absolute',
|
16 |
-
top:"-100px",
|
17 |
-
height:"3px",
|
18 |
-
width:"3px"
|
19 |
-
});
|
20 |
-
dojo.body().appendChild(savetextarea);
|
21 |
-
})();
|
22 |
-
}else{
|
23 |
-
//dojo.body() is not available before onLoad is fired
|
24 |
-
try{
|
25 |
-
dojo.doc.write('<textarea id="' + dijit._scopeName + '._editor.RichText.value" ' +
|
26 |
-
'style="display:none;position:absolute;top:-100px;left:-100px;height:3px;width:3px;overflow:hidden;"></textarea>');
|
27 |
-
}catch(e){ }
|
28 |
-
}
|
29 |
-
}
|
30 |
-
|
31 |
-
dojo.declare("dijit._editor.RichText", [dijit._Widget, dijit._CssStateMixin], {
|
32 |
-
constructor: function(params){
|
33 |
-
// summary:
|
34 |
-
// dijit._editor.RichText is the core of dijit.Editor, which provides basic
|
35 |
-
// WYSIWYG editing features.
|
36 |
-
//
|
37 |
-
// description:
|
38 |
-
// dijit._editor.RichText is the core of dijit.Editor, which provides basic
|
39 |
-
// WYSIWYG editing features. It also encapsulates the differences
|
40 |
-
// of different js engines for various browsers. Do not use this widget
|
41 |
-
// with an HTML <TEXTAREA> tag, since the browser unescapes XML escape characters,
|
42 |
-
// like <. This can have unexpected behavior and lead to security issues
|
43 |
-
// such as scripting attacks.
|
44 |
-
//
|
45 |
-
// tags:
|
46 |
-
// private
|
47 |
-
|
48 |
-
// contentPreFilters: Function(String)[]
|
49 |
-
// Pre content filter function register array.
|
50 |
-
// these filters will be executed before the actual
|
51 |
-
// editing area gets the html content.
|
52 |
-
this.contentPreFilters = [];
|
53 |
-
|
54 |
-
// contentPostFilters: Function(String)[]
|
55 |
-
// post content filter function register array.
|
56 |
-
// These will be used on the resulting html
|
57 |
-
// from contentDomPostFilters. The resulting
|
58 |
-
// content is the final html (returned by getValue()).
|
59 |
-
this.contentPostFilters = [];
|
60 |
-
|
61 |
-
// contentDomPreFilters: Function(DomNode)[]
|
62 |
-
// Pre content dom filter function register array.
|
63 |
-
// These filters are applied after the result from
|
64 |
-
// contentPreFilters are set to the editing area.
|
65 |
-
this.contentDomPreFilters = [];
|
66 |
-
|
67 |
-
// contentDomPostFilters: Function(DomNode)[]
|
68 |
-
// Post content dom filter function register array.
|
69 |
-
// These filters are executed on the editing area dom.
|
70 |
-
// The result from these will be passed to contentPostFilters.
|
71 |
-
this.contentDomPostFilters = [];
|
72 |
-
|
73 |
-
// editingAreaStyleSheets: dojo._URL[]
|
74 |
-
// array to store all the stylesheets applied to the editing area
|
75 |
-
this.editingAreaStyleSheets = [];
|
76 |
-
|
77 |
-
// Make a copy of this.events before we start writing into it, otherwise we
|
78 |
-
// will modify the prototype which leads to bad things on pages w/multiple editors
|
79 |
-
this.events = [].concat(this.events);
|
80 |
-
|
81 |
-
this._keyHandlers = {};
|
82 |
-
|
83 |
-
if(params && dojo.isString(params.value)){
|
84 |
-
this.value = params.value;
|
85 |
-
}
|
86 |
-
|
87 |
-
this.onLoadDeferred = new dojo.Deferred();
|
88 |
-
},
|
89 |
-
|
90 |
-
baseClass: "dijitEditor",
|
91 |
-
|
92 |
-
// inheritWidth: Boolean
|
93 |
-
// whether to inherit the parent's width or simply use 100%
|
94 |
-
inheritWidth: false,
|
95 |
-
|
96 |
-
// focusOnLoad: [deprecated] Boolean
|
97 |
-
// Focus into this widget when the page is loaded
|
98 |
-
focusOnLoad: false,
|
99 |
-
|
100 |
-
// name: String?
|
101 |
-
// Specifies the name of a (hidden) <textarea> node on the page that's used to save
|
102 |
-
// the editor content on page leave. Used to restore editor contents after navigating
|
103 |
-
// to a new page and then hitting the back button.
|
104 |
-
name: "",
|
105 |
-
|
106 |
-
// styleSheets: [const] String
|
107 |
-
// semicolon (";") separated list of css files for the editing area
|
108 |
-
styleSheets: "",
|
109 |
-
|
110 |
-
// height: String
|
111 |
-
// Set height to fix the editor at a specific height, with scrolling.
|
112 |
-
// By default, this is 300px. If you want to have the editor always
|
113 |
-
// resizes to accommodate the content, use AlwaysShowToolbar plugin
|
114 |
-
// and set height="". If this editor is used within a layout widget,
|
115 |
-
// set height="100%".
|
116 |
-
height: "300px",
|
117 |
-
|
118 |
-
// minHeight: String
|
119 |
-
// The minimum height that the editor should have.
|
120 |
-
minHeight: "1em",
|
121 |
-
|
122 |
-
// isClosed: [private] Boolean
|
123 |
-
isClosed: true,
|
124 |
-
|
125 |
-
// isLoaded: [private] Boolean
|
126 |
-
isLoaded: false,
|
127 |
-
|
128 |
-
// _SEPARATOR: [private] String
|
129 |
-
// Used to concat contents from multiple editors into a single string,
|
130 |
-
// so they can be saved into a single <textarea> node. See "name" attribute.
|
131 |
-
_SEPARATOR: "@@**%%__RICHTEXTBOUNDRY__%%**@@",
|
132 |
-
|
133 |
-
// _NAME_CONTENT_SEP: [private] String
|
134 |
-
// USed to separate name from content. Just a colon isn't safe.
|
135 |
-
_NAME_CONTENT_SEP: "@@**%%:%%**@@",
|
136 |
-
|
137 |
-
// onLoadDeferred: [readonly] dojo.Deferred
|
138 |
-
// Deferred which is fired when the editor finishes loading.
|
139 |
-
// Call myEditor.onLoadDeferred.then(callback) it to be informed
|
140 |
-
// when the rich-text area initialization is finalized.
|
141 |
-
onLoadDeferred: null,
|
142 |
-
|
143 |
-
// isTabIndent: Boolean
|
144 |
-
// Make tab key and shift-tab indent and outdent rather than navigating.
|
145 |
-
// Caution: sing this makes web pages inaccessible to users unable to use a mouse.
|
146 |
-
isTabIndent: false,
|
147 |
-
|
148 |
-
// disableSpellCheck: [const] Boolean
|
149 |
-
// When true, disables the browser's native spell checking, if supported.
|
150 |
-
// Works only in Firefox.
|
151 |
-
disableSpellCheck: false,
|
152 |
-
|
153 |
-
postCreate: function(){
|
154 |
-
if("textarea" == this.domNode.tagName.toLowerCase()){
|
155 |
-
console.warn("RichText should not be used with the TEXTAREA tag. See dijit._editor.RichText docs.");
|
156 |
-
}
|
157 |
-
|
158 |
-
// Push in the builtin filters now, making them the first executed, but not over-riding anything
|
159 |
-
// users passed in. See: #6062
|
160 |
-
this.contentPreFilters = [dojo.hitch(this, "_preFixUrlAttributes")].concat(this.contentPreFilters);
|
161 |
-
if(dojo.isMoz){
|
162 |
-
this.contentPreFilters = [this._normalizeFontStyle].concat(this.contentPreFilters);
|
163 |
-
this.contentPostFilters = [this._removeMozBogus].concat(this.contentPostFilters);
|
164 |
-
}
|
165 |
-
if(dojo.isWebKit){
|
166 |
-
// Try to clean up WebKit bogus artifacts. The inserted classes
|
167 |
-
// made by WebKit sometimes messes things up.
|
168 |
-
this.contentPreFilters = [this._removeWebkitBogus].concat(this.contentPreFilters);
|
169 |
-
this.contentPostFilters = [this._removeWebkitBogus].concat(this.contentPostFilters);
|
170 |
-
}
|
171 |
-
if(dojo.isIE){
|
172 |
-
// IE generates <strong> and <em> but we want to normalize to <b> and <i>
|
173 |
-
this.contentPostFilters = [this._normalizeFontStyle].concat(this.contentPostFilters);
|
174 |
-
}
|
175 |
-
this.inherited(arguments);
|
176 |
-
|
177 |
-
dojo.publish(dijit._scopeName + "._editor.RichText::init", [this]);
|
178 |
-
this.open();
|
179 |
-
this.setupDefaultShortcuts();
|
180 |
-
},
|
181 |
-
|
182 |
-
setupDefaultShortcuts: function(){
|
183 |
-
// summary:
|
184 |
-
// Add some default key handlers
|
185 |
-
// description:
|
186 |
-
// Overwrite this to setup your own handlers. The default
|
187 |
-
// implementation does not use Editor commands, but directly
|
188 |
-
// executes the builtin commands within the underlying browser
|
189 |
-
// support.
|
190 |
-
// tags:
|
191 |
-
// protected
|
192 |
-
var exec = dojo.hitch(this, function(cmd, arg){
|
193 |
-
return function(){
|
194 |
-
return !this.execCommand(cmd,arg);
|
195 |
-
};
|
196 |
-
});
|
197 |
-
|
198 |
-
var ctrlKeyHandlers = {
|
199 |
-
b: exec("bold"),
|
200 |
-
i: exec("italic"),
|
201 |
-
u: exec("underline"),
|
202 |
-
a: exec("selectall"),
|
203 |
-
s: function(){ this.save(true); },
|
204 |
-
m: function(){ this.isTabIndent = !this.isTabIndent; },
|
205 |
-
|
206 |
-
"1": exec("formatblock", "h1"),
|
207 |
-
"2": exec("formatblock", "h2"),
|
208 |
-
"3": exec("formatblock", "h3"),
|
209 |
-
"4": exec("formatblock", "h4"),
|
210 |
-
|
211 |
-
"\\": exec("insertunorderedlist")
|
212 |
-
};
|
213 |
-
|
214 |
-
if(!dojo.isIE){
|
215 |
-
ctrlKeyHandlers.Z = exec("redo"); //FIXME: undo?
|
216 |
-
}
|
217 |
-
|
218 |
-
for(var key in ctrlKeyHandlers){
|
219 |
-
this.addKeyHandler(key, true, false, ctrlKeyHandlers[key]);
|
220 |
-
}
|
221 |
-
},
|
222 |
-
|
223 |
-
// events: [private] String[]
|
224 |
-
// events which should be connected to the underlying editing area
|
225 |
-
events: ["onKeyPress", "onKeyDown", "onKeyUp"], // onClick handled specially
|
226 |
-
|
227 |
-
// captureEvents: [deprecated] String[]
|
228 |
-
// Events which should be connected to the underlying editing
|
229 |
-
// area, events in this array will be addListener with
|
230 |
-
// capture=true.
|
231 |
-
// TODO: looking at the code I don't see any distinction between events and captureEvents,
|
232 |
-
// so get rid of this for 2.0 if not sooner
|
233 |
-
captureEvents: [],
|
234 |
-
|
235 |
-
_editorCommandsLocalized: false,
|
236 |
-
_localizeEditorCommands: function(){
|
237 |
-
// summary:
|
238 |
-
// When IE is running in a non-English locale, the API actually changes,
|
239 |
-
// so that we have to say (for example) danraku instead of p (for paragraph).
|
240 |
-
// Handle that here.
|
241 |
-
// tags:
|
242 |
-
// private
|
243 |
-
if(dijit._editor._editorCommandsLocalized){
|
244 |
-
// Use the already generate cache of mappings.
|
245 |
-
this._local2NativeFormatNames = dijit._editor._local2NativeFormatNames;
|
246 |
-
this._native2LocalFormatNames = dijit._editor._native2LocalFormatNames;
|
247 |
-
return;
|
248 |
-
}
|
249 |
-
dijit._editor._editorCommandsLocalized = true;
|
250 |
-
dijit._editor._local2NativeFormatNames = {};
|
251 |
-
dijit._editor._native2LocalFormatNames = {};
|
252 |
-
this._local2NativeFormatNames = dijit._editor._local2NativeFormatNames;
|
253 |
-
this._native2LocalFormatNames = dijit._editor._native2LocalFormatNames;
|
254 |
-
//in IE, names for blockformat is locale dependent, so we cache the values here
|
255 |
-
|
256 |
-
//put p after div, so if IE returns Normal, we show it as paragraph
|
257 |
-
//We can distinguish p and div if IE returns Normal, however, in order to detect that,
|
258 |
-
//we have to call this.document.selection.createRange().parentElement() or such, which
|
259 |
-
//could slow things down. Leave it as it is for now
|
260 |
-
var formats = ['div', 'p', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'address'];
|
261 |
-
var localhtml = "", format, i=0;
|
262 |
-
while((format=formats[i++])){
|
263 |
-
//append a <br> after each element to separate the elements more reliably
|
264 |
-
if(format.charAt(1) !== 'l'){
|
265 |
-
localhtml += "<"+format+"><span>content</span></"+format+"><br/>";
|
266 |
-
}else{
|
267 |
-
localhtml += "<"+format+"><li>content</li></"+format+"><br/>";
|
268 |
-
}
|
269 |
-
}
|
270 |
-
// queryCommandValue returns empty if we hide editNode, so move it out of screen temporary
|
271 |
-
// Also, IE9 does weird stuff unless we do it inside the editor iframe.
|
272 |
-
var style = { position: "absolute", top: "0px", zIndex: 10, opacity: 0.01 };
|
273 |
-
var div = dojo.create('div', {style: style, innerHTML: localhtml});
|
274 |
-
dojo.body().appendChild(div);
|
275 |
-
|
276 |
-
// IE9 has a timing issue with doing this right after setting
|
277 |
-
// the inner HTML, so put a delay in.
|
278 |
-
var inject = dojo.hitch(this, function(){
|
279 |
-
var node = div.firstChild;
|
280 |
-
while(node){
|
281 |
-
try{
|
282 |
-
dijit._editor.selection.selectElement(node.firstChild);
|
283 |
-
var nativename = node.tagName.toLowerCase();
|
284 |
-
this._local2NativeFormatNames[nativename] = document.queryCommandValue("formatblock");
|
285 |
-
this._native2LocalFormatNames[this._local2NativeFormatNames[nativename]] = nativename;
|
286 |
-
node = node.nextSibling.nextSibling;
|
287 |
-
//console.log("Mapped: ", nativename, " to: ", this._local2NativeFormatNames[nativename]);
|
288 |
-
}catch(e) { /*Sqelch the occasional IE9 error */ }
|
289 |
-
}
|
290 |
-
div.parentNode.removeChild(div);
|
291 |
-
div.innerHTML = "";
|
292 |
-
});
|
293 |
-
setTimeout(inject, 0);
|
294 |
-
},
|
295 |
-
|
296 |
-
open: function(/*DomNode?*/ element){
|
297 |
-
// summary:
|
298 |
-
// Transforms the node referenced in this.domNode into a rich text editing
|
299 |
-
// node.
|
300 |
-
// description:
|
301 |
-
// Sets up the editing area asynchronously. This will result in
|
302 |
-
// the creation and replacement with an iframe.
|
303 |
-
// tags:
|
304 |
-
// private
|
305 |
-
|
306 |
-
if(!this.onLoadDeferred || this.onLoadDeferred.fired >= 0){
|
307 |
-
this.onLoadDeferred = new dojo.Deferred();
|
308 |
-
}
|
309 |
-
|
310 |
-
if(!this.isClosed){ this.close(); }
|
311 |
-
dojo.publish(dijit._scopeName + "._editor.RichText::open", [ this ]);
|
312 |
-
|
313 |
-
if(arguments.length == 1 && element.nodeName){ // else unchanged
|
314 |
-
this.domNode = element;
|
315 |
-
}
|
316 |
-
|
317 |
-
var dn = this.domNode;
|
318 |
-
|
319 |
-
// "html" will hold the innerHTML of the srcNodeRef and will be used to
|
320 |
-
// initialize the editor.
|
321 |
-
var html;
|
322 |
-
|
323 |
-
if(dojo.isString(this.value)){
|
324 |
-
// Allow setting the editor content programmatically instead of
|
325 |
-
// relying on the initial content being contained within the target
|
326 |
-
// domNode.
|
327 |
-
html = this.value;
|
328 |
-
delete this.value;
|
329 |
-
dn.innerHTML = "";
|
330 |
-
}else if(dn.nodeName && dn.nodeName.toLowerCase() == "textarea"){
|
331 |
-
// if we were created from a textarea, then we need to create a
|
332 |
-
// new editing harness node.
|
333 |
-
var ta = (this.textarea = dn);
|
334 |
-
this.name = ta.name;
|
335 |
-
html = ta.value;
|
336 |
-
dn = this.domNode = dojo.doc.createElement("div");
|
337 |
-
dn.setAttribute('widgetId', this.id);
|
338 |
-
ta.removeAttribute('widgetId');
|
339 |
-
dn.cssText = ta.cssText;
|
340 |
-
dn.className += " " + ta.className;
|
341 |
-
dojo.place(dn, ta, "before");
|
342 |
-
var tmpFunc = dojo.hitch(this, function(){
|
343 |
-
//some browsers refuse to submit display=none textarea, so
|
344 |
-
//move the textarea off screen instead
|
345 |
-
dojo.style(ta, {
|
346 |
-
display: "block",
|
347 |
-
position: "absolute",
|
348 |
-
top: "-1000px"
|
349 |
-
});
|
350 |
-
|
351 |
-
if(dojo.isIE){ //nasty IE bug: abnormal formatting if overflow is not hidden
|
352 |
-
var s = ta.style;
|
353 |
-
this.__overflow = s.overflow;
|
354 |
-
s.overflow = "hidden";
|
355 |
-
}
|
356 |
-
});
|
357 |
-
if(dojo.isIE){
|
358 |
-
setTimeout(tmpFunc, 10);
|
359 |
-
}else{
|
360 |
-
tmpFunc();
|
361 |
-
}
|
362 |
-
|
363 |
-
if(ta.form){
|
364 |
-
var resetValue = ta.value;
|
365 |
-
this.reset = function(){
|
366 |
-
var current = this.getValue();
|
367 |
-
if(current != resetValue){
|
368 |
-
this.replaceValue(resetValue);
|
369 |
-
}
|
370 |
-
};
|
371 |
-
dojo.connect(ta.form, "onsubmit", this, function(){
|
372 |
-
// Copy value to the <textarea> so it gets submitted along with form.
|
373 |
-
// FIXME: should we be calling close() here instead?
|
374 |
-
dojo.attr(ta, 'disabled', this.disabled); // don't submit the value if disabled
|
375 |
-
ta.value = this.getValue();
|
376 |
-
});
|
377 |
-
}
|
378 |
-
}else{
|
379 |
-
html = dijit._editor.getChildrenHtml(dn);
|
380 |
-
dn.innerHTML = "";
|
381 |
-
}
|
382 |
-
|
383 |
-
var content = dojo.contentBox(dn);
|
384 |
-
this._oldHeight = content.h;
|
385 |
-
this._oldWidth = content.w;
|
386 |
-
|
387 |
-
this.value = html;
|
388 |
-
|
389 |
-
// If we're a list item we have to put in a blank line to force the
|
390 |
-
// bullet to nicely align at the top of text
|
391 |
-
if(dn.nodeName && dn.nodeName == "LI"){
|
392 |
-
dn.innerHTML = " <br>";
|
393 |
-
}
|
394 |
-
|
395 |
-
// Construct the editor div structure.
|
396 |
-
this.header = dn.ownerDocument.createElement("div");
|
397 |
-
dn.appendChild(this.header);
|
398 |
-
this.editingArea = dn.ownerDocument.createElement("div");
|
399 |
-
dn.appendChild(this.editingArea);
|
400 |
-
this.footer = dn.ownerDocument.createElement("div");
|
401 |
-
dn.appendChild(this.footer);
|
402 |
-
|
403 |
-
if(!this.name){
|
404 |
-
this.name = this.id + "_AUTOGEN";
|
405 |
-
}
|
406 |
-
|
407 |
-
// User has pressed back/forward button so we lost the text in the editor, but it's saved
|
408 |
-
// in a hidden <textarea> (which contains the data for all the editors on this page),
|
409 |
-
// so get editor value from there
|
410 |
-
if(this.name !== "" && (!dojo.config["useXDomain"] || dojo.config["allowXdRichTextSave"])){
|
411 |
-
var saveTextarea = dojo.byId(dijit._scopeName + "._editor.RichText.value");
|
412 |
-
if(saveTextarea && saveTextarea.value !== ""){
|
413 |
-
var datas = saveTextarea.value.split(this._SEPARATOR), i=0, dat;
|
414 |
-
while((dat=datas[i++])){
|
415 |
-
var data = dat.split(this._NAME_CONTENT_SEP);
|
416 |
-
if(data[0] == this.name){
|
417 |
-
html = data[1];
|
418 |
-
datas = datas.splice(i, 1);
|
419 |
-
saveTextarea.value = datas.join(this._SEPARATOR);
|
420 |
-
break;
|
421 |
-
}
|
422 |
-
}
|
423 |
-
}
|
424 |
-
|
425 |
-
if(!dijit._editor._globalSaveHandler){
|
426 |
-
dijit._editor._globalSaveHandler = {};
|
427 |
-
dojo.addOnUnload(function() {
|
428 |
-
var id;
|
429 |
-
for(id in dijit._editor._globalSaveHandler){
|
430 |
-
var f = dijit._editor._globalSaveHandler[id];
|
431 |
-
if(dojo.isFunction(f)){
|
432 |
-
f();
|
433 |
-
}
|
434 |
-
}
|
435 |
-
});
|
436 |
-
}
|
437 |
-
dijit._editor._globalSaveHandler[this.id] = dojo.hitch(this, "_saveContent");
|
438 |
-
}
|
439 |
-
|
440 |
-
this.isClosed = false;
|
441 |
-
|
442 |
-
var ifr = (this.editorObject = this.iframe = dojo.doc.createElement('iframe'));
|
443 |
-
ifr.id = this.id+"_iframe";
|
444 |
-
this._iframeSrc = this._getIframeDocTxt();
|
445 |
-
ifr.style.border = "none";
|
446 |
-
ifr.style.width = "100%";
|
447 |
-
if(this._layoutMode){
|
448 |
-
// iframe should be 100% height, thus getting it's height from surrounding
|
449 |
-
// <div> (which has the correct height set by Editor)
|
450 |
-
ifr.style.height = "100%";
|
451 |
-
}else{
|
452 |
-
if(dojo.isIE >= 7){
|
453 |
-
if(this.height){
|
454 |
-
ifr.style.height = this.height;
|
455 |
-
}
|
456 |
-
if(this.minHeight){
|
457 |
-
ifr.style.minHeight = this.minHeight;
|
458 |
-
}
|
459 |
-
}else{
|
460 |
-
ifr.style.height = this.height ? this.height : this.minHeight;
|
461 |
-
}
|
462 |
-
}
|
463 |
-
ifr.frameBorder = 0;
|
464 |
-
ifr._loadFunc = dojo.hitch( this, function(win){
|
465 |
-
this.window = win;
|
466 |
-
this.document = this.window.document;
|
467 |
-
|
468 |
-
if(dojo.isIE){
|
469 |
-
this._localizeEditorCommands();
|
470 |
-
}
|
471 |
-
|
472 |
-
// Do final setup and set initial contents of editor
|
473 |
-
this.onLoad(html);
|
474 |
-
});
|
475 |
-
|
476 |
-
// Set the iframe's initial (blank) content.
|
477 |
-
var s = 'javascript:parent.' + dijit._scopeName + '.byId("'+this.id+'")._iframeSrc';
|
478 |
-
ifr.setAttribute('src', s);
|
479 |
-
this.editingArea.appendChild(ifr);
|
480 |
-
|
481 |
-
if(dojo.isSafari <= 4){
|
482 |
-
var src = ifr.getAttribute("src");
|
483 |
-
if(!src || src.indexOf("javascript") == -1){
|
484 |
-
// Safari 4 and earlier sometimes act oddly
|
485 |
-
// So we have to set it again.
|
486 |
-
setTimeout(function(){ifr.setAttribute('src', s);},0);
|
487 |
-
}
|
488 |
-
}
|
489 |
-
|
490 |
-
// TODO: this is a guess at the default line-height, kinda works
|
491 |
-
if(dn.nodeName == "LI"){
|
492 |
-
dn.lastChild.style.marginTop = "-1.2em";
|
493 |
-
}
|
494 |
-
|
495 |
-
dojo.addClass(this.domNode, this.baseClass);
|
496 |
-
},
|
497 |
-
|
498 |
-
//static cache variables shared among all instance of this class
|
499 |
-
_local2NativeFormatNames: {},
|
500 |
-
_native2LocalFormatNames: {},
|
501 |
-
|
502 |
-
_getIframeDocTxt: function(){
|
503 |
-
// summary:
|
504 |
-
// Generates the boilerplate text of the document inside the iframe (ie, <html><head>...</head><body/></html>).
|
505 |
-
// Editor content (if not blank) should be added afterwards.
|
506 |
-
// tags:
|
507 |
-
// private
|
508 |
-
var _cs = dojo.getComputedStyle(this.domNode);
|
509 |
-
|
510 |
-
// The contents inside of <body>. The real contents are set later via a call to setValue().
|
511 |
-
var html = "";
|
512 |
-
var setBodyId = true;
|
513 |
-
if(dojo.isIE || dojo.isWebKit || (!this.height && !dojo.isMoz)){
|
514 |
-
// In auto-expand mode, need a wrapper div for AlwaysShowToolbar plugin to correctly
|
515 |
-
// expand/contract the editor as the content changes.
|
516 |
-
html = "<div id='dijitEditorBody'></div>";
|
517 |
-
setBodyId = false;
|
518 |
-
}else if(dojo.isMoz){
|
519 |
-
// workaround bug where can't select then delete text (until user types something
|
520 |
-
// into the editor)... and/or issue where typing doesn't erase selected text
|
521 |
-
this._cursorToStart = true;
|
522 |
-
html = " ";
|
523 |
-
}
|
524 |
-
|
525 |
-
var font = [ _cs.fontWeight, _cs.fontSize, _cs.fontFamily ].join(" ");
|
526 |
-
|
527 |
-
// line height is tricky - applying a units value will mess things up.
|
528 |
-
// if we can't get a non-units value, bail out.
|
529 |
-
var lineHeight = _cs.lineHeight;
|
530 |
-
if(lineHeight.indexOf("px") >= 0){
|
531 |
-
lineHeight = parseFloat(lineHeight)/parseFloat(_cs.fontSize);
|
532 |
-
// console.debug(lineHeight);
|
533 |
-
}else if(lineHeight.indexOf("em")>=0){
|
534 |
-
lineHeight = parseFloat(lineHeight);
|
535 |
-
}else{
|
536 |
-
// If we can't get a non-units value, just default
|
537 |
-
// it to the CSS spec default of 'normal'. Seems to
|
538 |
-
// work better, esp on IE, than '1.0'
|
539 |
-
lineHeight = "normal";
|
540 |
-
}
|
541 |
-
var userStyle = "";
|
542 |
-
var self = this;
|
543 |
-
this.style.replace(/(^|;)\s*(line-|font-?)[^;]+/ig, function(match){
|
544 |
-
match = match.replace(/^;/ig,"") + ';';
|
545 |
-
var s = match.split(":")[0];
|
546 |
-
if(s){
|
547 |
-
s = dojo.trim(s);
|
548 |
-
s = s.toLowerCase();
|
549 |
-
var i;
|
550 |
-
var sC = "";
|
551 |
-
for(i = 0; i < s.length; i++){
|
552 |
-
var c = s.charAt(i);
|
553 |
-
switch(c){
|
554 |
-
case "-":
|
555 |
-
i++;
|
556 |
-
c = s.charAt(i).toUpperCase();
|
557 |
-
default:
|
558 |
-
sC += c;
|
559 |
-
}
|
560 |
-
}
|
561 |
-
dojo.style(self.domNode, sC, "");
|
562 |
-
}
|
563 |
-
userStyle += match + ';';
|
564 |
-
});
|
565 |
-
|
566 |
-
|
567 |
-
// need to find any associated label element and update iframe document title
|
568 |
-
var label=dojo.query('label[for="'+this.id+'"]');
|
569 |
-
|
570 |
-
return [
|
571 |
-
this.isLeftToRight() ? "<html>\n<head>\n" : "<html dir='rtl'>\n<head>\n",
|
572 |
-
|
573 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
574 |
-
// (dojo.isMoz && label.length ? "<title>" + label[0].innerHTML + "</title>\n" : ""),
|
575 |
-
// FIXED:
|
576 |
-
|
577 |
-
"<meta http-equiv='Content-Type' content='text/html'>\n",
|
578 |
-
"<style>\n",
|
579 |
-
"\tbody,html {\n",
|
580 |
-
"\t\tbackground:transparent;\n",
|
581 |
-
"\t\tpadding: 1px 0 0 0;\n",
|
582 |
-
"\t\tmargin: -1px 0 0 0;\n", // remove extraneous vertical scrollbar on safari and firefox
|
583 |
-
|
584 |
-
// Set the html/body sizing. Webkit always needs this, other browsers
|
585 |
-
// only set it when height is defined (not auto-expanding), otherwise
|
586 |
-
// scrollers do not appear.
|
587 |
-
((dojo.isWebKit)?"\t\twidth: 100%;\n":""),
|
588 |
-
((dojo.isWebKit)?"\t\theight: 100%;\n":""),
|
589 |
-
"\t}\n",
|
590 |
-
|
591 |
-
// TODO: left positioning will cause contents to disappear out of view
|
592 |
-
// if it gets too wide for the visible area
|
593 |
-
"\tbody{\n",
|
594 |
-
"\t\ttop:0px;\n",
|
595 |
-
"\t\tleft:0px;\n",
|
596 |
-
"\t\tright:0px;\n",
|
597 |
-
"\t\tfont:", font, ";\n",
|
598 |
-
((this.height||dojo.isOpera) ? "" : "\t\tposition: fixed;\n"),
|
599 |
-
// FIXME: IE 6 won't understand min-height?
|
600 |
-
"\t\tmin-height:", this.minHeight, ";\n",
|
601 |
-
"\t\tline-height:", lineHeight,";\n",
|
602 |
-
"\t}\n",
|
603 |
-
"\tp{ margin: 1em 0; }\n",
|
604 |
-
|
605 |
-
// Determine how scrollers should be applied. In autoexpand mode (height = "") no scrollers on y at all.
|
606 |
-
// But in fixed height mode we want both x/y scrollers. Also, if it's using wrapping div and in auto-expand
|
607 |
-
// (Mainly IE) we need to kill the y scroller on body and html.
|
608 |
-
(!setBodyId && !this.height ? "\tbody,html {overflow-y: hidden;}\n" : ""),
|
609 |
-
"\t#dijitEditorBody{overflow-x: auto; overflow-y:" + (this.height ? "auto;" : "hidden;") + " outline: 0px;}\n",
|
610 |
-
"\tli > ul:-moz-first-node, li > ol:-moz-first-node{ padding-top: 1.2em; }\n",
|
611 |
-
// Can't set min-height in IE9, it puts layout on li, which puts move/resize handles.
|
612 |
-
(!dojo.isIE ? "\tli{ min-height:1.2em; }\n" : ""),
|
613 |
-
"</style>\n",
|
614 |
-
this._applyEditingAreaStyleSheets(),"\n",
|
615 |
-
"</head>\n<body ",
|
616 |
-
(setBodyId?"id='dijitEditorBody' ":""),
|
617 |
-
"onload='frameElement._loadFunc(window,document)' style='"+userStyle+"'>", html, "</body>\n</html>"
|
618 |
-
].join(""); // String
|
619 |
-
},
|
620 |
-
|
621 |
-
_applyEditingAreaStyleSheets: function(){
|
622 |
-
// summary:
|
623 |
-
// apply the specified css files in styleSheets
|
624 |
-
// tags:
|
625 |
-
// private
|
626 |
-
var files = [];
|
627 |
-
if(this.styleSheets){
|
628 |
-
files = this.styleSheets.split(';');
|
629 |
-
this.styleSheets = '';
|
630 |
-
}
|
631 |
-
|
632 |
-
//empty this.editingAreaStyleSheets here, as it will be filled in addStyleSheet
|
633 |
-
files = files.concat(this.editingAreaStyleSheets);
|
634 |
-
this.editingAreaStyleSheets = [];
|
635 |
-
|
636 |
-
var text='', i=0, url;
|
637 |
-
while((url=files[i++])){
|
638 |
-
var abstring = (new dojo._Url(dojo.global.location, url)).toString();
|
639 |
-
this.editingAreaStyleSheets.push(abstring);
|
640 |
-
text += '<link rel="stylesheet" type="text/css" href="'+abstring+'"/>';
|
641 |
-
}
|
642 |
-
return text;
|
643 |
-
},
|
644 |
-
|
645 |
-
addStyleSheet: function(/*dojo._Url*/ uri){
|
646 |
-
// summary:
|
647 |
-
// add an external stylesheet for the editing area
|
648 |
-
// uri:
|
649 |
-
// A dojo.uri.Uri pointing to the url of the external css file
|
650 |
-
var url=uri.toString();
|
651 |
-
|
652 |
-
//if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe
|
653 |
-
if(url.charAt(0) == '.' || (url.charAt(0) != '/' && !uri.host)){
|
654 |
-
url = (new dojo._Url(dojo.global.location, url)).toString();
|
655 |
-
}
|
656 |
-
|
657 |
-
if(dojo.indexOf(this.editingAreaStyleSheets, url) > -1){
|
658 |
-
// console.debug("dijit._editor.RichText.addStyleSheet: Style sheet "+url+" is already applied");
|
659 |
-
return;
|
660 |
-
}
|
661 |
-
|
662 |
-
this.editingAreaStyleSheets.push(url);
|
663 |
-
this.onLoadDeferred.addCallback(dojo.hitch(this, function(){
|
664 |
-
if(this.document.createStyleSheet){ //IE
|
665 |
-
this.document.createStyleSheet(url);
|
666 |
-
}else{ //other browser
|
667 |
-
var head = this.document.getElementsByTagName("head")[0];
|
668 |
-
var stylesheet = this.document.createElement("link");
|
669 |
-
stylesheet.rel="stylesheet";
|
670 |
-
stylesheet.type="text/css";
|
671 |
-
stylesheet.href=url;
|
672 |
-
head.appendChild(stylesheet);
|
673 |
-
}
|
674 |
-
}));
|
675 |
-
},
|
676 |
-
|
677 |
-
removeStyleSheet: function(/*dojo._Url*/ uri){
|
678 |
-
// summary:
|
679 |
-
// remove an external stylesheet for the editing area
|
680 |
-
var url=uri.toString();
|
681 |
-
//if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe
|
682 |
-
if(url.charAt(0) == '.' || (url.charAt(0) != '/' && !uri.host)){
|
683 |
-
url = (new dojo._Url(dojo.global.location, url)).toString();
|
684 |
-
}
|
685 |
-
var index = dojo.indexOf(this.editingAreaStyleSheets, url);
|
686 |
-
if(index == -1){
|
687 |
-
// console.debug("dijit._editor.RichText.removeStyleSheet: Style sheet "+url+" has not been applied");
|
688 |
-
return;
|
689 |
-
}
|
690 |
-
delete this.editingAreaStyleSheets[index];
|
691 |
-
dojo.withGlobal(this.window,'query', dojo, ['link:[href="'+url+'"]']).orphan();
|
692 |
-
},
|
693 |
-
|
694 |
-
// disabled: Boolean
|
695 |
-
// The editor is disabled; the text cannot be changed.
|
696 |
-
disabled: false,
|
697 |
-
|
698 |
-
_mozSettingProps: {'styleWithCSS':false},
|
699 |
-
_setDisabledAttr: function(/*Boolean*/ value){
|
700 |
-
value = !!value;
|
701 |
-
this._set("disabled", value);
|
702 |
-
if(!this.isLoaded){ return; } // this method requires init to be complete
|
703 |
-
if(dojo.isIE || dojo.isWebKit || dojo.isOpera){
|
704 |
-
var preventIEfocus = dojo.isIE && (this.isLoaded || !this.focusOnLoad);
|
705 |
-
if(preventIEfocus){ this.editNode.unselectable = "on"; }
|
706 |
-
this.editNode.contentEditable = !value;
|
707 |
-
if(preventIEfocus){
|
708 |
-
var _this = this;
|
709 |
-
setTimeout(function(){ _this.editNode.unselectable = "off"; }, 0);
|
710 |
-
}
|
711 |
-
}else{ //moz
|
712 |
-
try{
|
713 |
-
this.document.designMode=(value?'off':'on');
|
714 |
-
}catch(e){ return; } // ! _disabledOK
|
715 |
-
if(!value && this._mozSettingProps){
|
716 |
-
var ps = this._mozSettingProps;
|
717 |
-
for(var n in ps){
|
718 |
-
if(ps.hasOwnProperty(n)){
|
719 |
-
try{
|
720 |
-
this.document.execCommand(n,false,ps[n]);
|
721 |
-
}catch(e2){}
|
722 |
-
}
|
723 |
-
}
|
724 |
-
}
|
725 |
-
// this.document.execCommand('contentReadOnly', false, value);
|
726 |
-
// if(value){
|
727 |
-
// this.blur(); //to remove the blinking caret
|
728 |
-
// }
|
729 |
-
}
|
730 |
-
this._disabledOK = true;
|
731 |
-
},
|
732 |
-
|
733 |
-
/* Event handlers
|
734 |
-
*****************/
|
735 |
-
|
736 |
-
onLoad: function(/*String*/ html){
|
737 |
-
// summary:
|
738 |
-
// Handler after the iframe finishes loading.
|
739 |
-
// html: String
|
740 |
-
// Editor contents should be set to this value
|
741 |
-
// tags:
|
742 |
-
// protected
|
743 |
-
|
744 |
-
// TODO: rename this to _onLoad, make empty public onLoad() method, deprecate/make protected onLoadDeferred handler?
|
745 |
-
|
746 |
-
if(!this.window.__registeredWindow){
|
747 |
-
this.window.__registeredWindow = true;
|
748 |
-
this._iframeRegHandle = dijit.registerIframe(this.iframe);
|
749 |
-
}
|
750 |
-
if(!dojo.isIE && !dojo.isWebKit && (this.height || dojo.isMoz)){
|
751 |
-
this.editNode=this.document.body;
|
752 |
-
}else{
|
753 |
-
// there's a wrapper div around the content, see _getIframeDocTxt().
|
754 |
-
this.editNode=this.document.body.firstChild;
|
755 |
-
var _this = this;
|
756 |
-
if(dojo.isIE){ // #4996 IE wants to focus the BODY tag
|
757 |
-
this.tabStop = dojo.create('div', { tabIndex: -1 }, this.editingArea);
|
758 |
-
this.iframe.onfocus = function(){ _this.editNode.setActive(); };
|
759 |
-
}
|
760 |
-
}
|
761 |
-
this.focusNode = this.editNode; // for InlineEditBox
|
762 |
-
|
763 |
-
|
764 |
-
var events = this.events.concat(this.captureEvents);
|
765 |
-
var ap = this.iframe ? this.document : this.editNode;
|
766 |
-
dojo.forEach(events, function(item){
|
767 |
-
this.connect(ap, item.toLowerCase(), item);
|
768 |
-
}, this);
|
769 |
-
|
770 |
-
this.connect(ap, "onmouseup", "onClick"); // mouseup in the margin does not generate an onclick event
|
771 |
-
|
772 |
-
if(dojo.isIE){ // IE contentEditable
|
773 |
-
this.connect(this.document, "onmousedown", "_onIEMouseDown"); // #4996 fix focus
|
774 |
-
|
775 |
-
// give the node Layout on IE
|
776 |
-
// TODO: this may no longer be needed, since we've reverted IE to using an iframe,
|
777 |
-
// not contentEditable. Removing it would also probably remove the need for creating
|
778 |
-
// the extra <div> in _getIframeDocTxt()
|
779 |
-
this.editNode.style.zoom = 1.0;
|
780 |
-
}else{
|
781 |
-
this.connect(this.document, "onmousedown", function(){
|
782 |
-
// Clear the moveToStart focus, as mouse
|
783 |
-
// down will set cursor point. Required to properly
|
784 |
-
// work with selection/position driven plugins and clicks in
|
785 |
-
// the window. refs: #10678
|
786 |
-
delete this._cursorToStart;
|
787 |
-
});
|
788 |
-
}
|
789 |
-
|
790 |
-
if(dojo.isWebKit){
|
791 |
-
//WebKit sometimes doesn't fire right on selections, so the toolbar
|
792 |
-
//doesn't update right. Therefore, help it out a bit with an additional
|
793 |
-
//listener. A mouse up will typically indicate a display change, so fire this
|
794 |
-
//and get the toolbar to adapt. Reference: #9532
|
795 |
-
this._webkitListener = this.connect(this.document, "onmouseup", "onDisplayChanged");
|
796 |
-
this.connect(this.document, "onmousedown", function(e){
|
797 |
-
var t = e.target;
|
798 |
-
if(t && (t === this.document.body || t === this.document)){
|
799 |
-
// Since WebKit uses the inner DIV, we need to check and set position.
|
800 |
-
// See: #12024 as to why the change was made.
|
801 |
-
setTimeout(dojo.hitch(this, "placeCursorAtEnd"), 0);
|
802 |
-
}
|
803 |
-
});
|
804 |
-
}
|
805 |
-
|
806 |
-
if(dojo.isIE){
|
807 |
-
// Try to make sure 'hidden' elements aren't visible in edit mode (like browsers other than IE
|
808 |
-
// do). See #9103
|
809 |
-
try{
|
810 |
-
this.document.execCommand('RespectVisibilityInDesign', true, null);
|
811 |
-
}catch(e){/* squelch */}
|
812 |
-
}
|
813 |
-
|
814 |
-
this.isLoaded = true;
|
815 |
-
|
816 |
-
this.set('disabled', this.disabled); // initialize content to editable (or not)
|
817 |
-
|
818 |
-
// Note that setValue() call will only work after isLoaded is set to true (above)
|
819 |
-
|
820 |
-
// Set up a function to allow delaying the setValue until a callback is fired
|
821 |
-
// This ensures extensions like dijit.Editor have a way to hold the value set
|
822 |
-
// until plugins load (and do things like register filters).
|
823 |
-
var setContent = dojo.hitch(this, function(){
|
824 |
-
this.setValue(html);
|
825 |
-
if(this.onLoadDeferred){
|
826 |
-
this.onLoadDeferred.callback(true);
|
827 |
-
}
|
828 |
-
this.onDisplayChanged();
|
829 |
-
if(this.focusOnLoad){
|
830 |
-
// after the document loads, then set focus after updateInterval expires so that
|
831 |
-
// onNormalizedDisplayChanged has run to avoid input caret issues
|
832 |
-
dojo.addOnLoad(dojo.hitch(this, function(){ setTimeout(dojo.hitch(this, "focus"), this.updateInterval); }));
|
833 |
-
}
|
834 |
-
// Save off the initial content now
|
835 |
-
this.value = this.getValue(true);
|
836 |
-
});
|
837 |
-
if(this.setValueDeferred){
|
838 |
-
this.setValueDeferred.addCallback(setContent);
|
839 |
-
}else{
|
840 |
-
setContent();
|
841 |
-
}
|
842 |
-
},
|
843 |
-
|
844 |
-
onKeyDown: function(/* Event */ e){
|
845 |
-
// summary:
|
846 |
-
// Handler for onkeydown event
|
847 |
-
// tags:
|
848 |
-
// protected
|
849 |
-
|
850 |
-
// we need this event at the moment to get the events from control keys
|
851 |
-
// such as the backspace. It might be possible to add this to Dojo, so that
|
852 |
-
// keyPress events can be emulated by the keyDown and keyUp detection.
|
853 |
-
|
854 |
-
if(e.keyCode === dojo.keys.TAB && this.isTabIndent ){
|
855 |
-
dojo.stopEvent(e); //prevent tab from moving focus out of editor
|
856 |
-
|
857 |
-
// FIXME: this is a poor-man's indent/outdent. It would be
|
858 |
-
// better if it added 4 " " chars in an undoable way.
|
859 |
-
// Unfortunately pasteHTML does not prove to be undoable
|
860 |
-
if(this.queryCommandEnabled((e.shiftKey ? "outdent" : "indent"))){
|
861 |
-
this.execCommand((e.shiftKey ? "outdent" : "indent"));
|
862 |
-
}
|
863 |
-
}
|
864 |
-
if(dojo.isIE){
|
865 |
-
if(e.keyCode == dojo.keys.TAB && !this.isTabIndent){
|
866 |
-
if(e.shiftKey && !e.ctrlKey && !e.altKey){
|
867 |
-
// focus the BODY so the browser will tab away from it instead
|
868 |
-
this.iframe.focus();
|
869 |
-
}else if(!e.shiftKey && !e.ctrlKey && !e.altKey){
|
870 |
-
// focus the BODY so the browser will tab away from it instead
|
871 |
-
this.tabStop.focus();
|
872 |
-
}
|
873 |
-
}else if(e.keyCode === dojo.keys.BACKSPACE && this.document.selection.type === "Control"){
|
874 |
-
// IE has a bug where if a non-text object is selected in the editor,
|
875 |
-
// hitting backspace would act as if the browser's back button was
|
876 |
-
// clicked instead of deleting the object. see #1069
|
877 |
-
dojo.stopEvent(e);
|
878 |
-
this.execCommand("delete");
|
879 |
-
}else if((65 <= e.keyCode && e.keyCode <= 90) ||
|
880 |
-
(e.keyCode>=37 && e.keyCode<=40) // FIXME: get this from connect() instead!
|
881 |
-
){ //arrow keys
|
882 |
-
e.charCode = e.keyCode;
|
883 |
-
this.onKeyPress(e);
|
884 |
-
}
|
885 |
-
}
|
886 |
-
return true;
|
887 |
-
},
|
888 |
-
|
889 |
-
onKeyUp: function(e){
|
890 |
-
// summary:
|
891 |
-
// Handler for onkeyup event
|
892 |
-
// tags:
|
893 |
-
// callback
|
894 |
-
return;
|
895 |
-
},
|
896 |
-
|
897 |
-
setDisabled: function(/*Boolean*/ disabled){
|
898 |
-
// summary:
|
899 |
-
// Deprecated, use set('disabled', ...) instead.
|
900 |
-
// tags:
|
901 |
-
// deprecated
|
902 |
-
dojo.deprecated('dijit.Editor::setDisabled is deprecated','use dijit.Editor::attr("disabled",boolean) instead', 2.0);
|
903 |
-
this.set('disabled',disabled);
|
904 |
-
},
|
905 |
-
_setValueAttr: function(/*String*/ value){
|
906 |
-
// summary:
|
907 |
-
// Registers that attr("value", foo) should call setValue(foo)
|
908 |
-
this.setValue(value);
|
909 |
-
},
|
910 |
-
_setDisableSpellCheckAttr: function(/*Boolean*/ disabled){
|
911 |
-
if(this.document){
|
912 |
-
dojo.attr(this.document.body, "spellcheck", !disabled);
|
913 |
-
}else{
|
914 |
-
// try again after the editor is finished loading
|
915 |
-
this.onLoadDeferred.addCallback(dojo.hitch(this, function(){
|
916 |
-
dojo.attr(this.document.body, "spellcheck", !disabled);
|
917 |
-
}));
|
918 |
-
}
|
919 |
-
this._set("disableSpellCheck", disabled);
|
920 |
-
},
|
921 |
-
|
922 |
-
onKeyPress: function(e){
|
923 |
-
// summary:
|
924 |
-
// Handle the various key events
|
925 |
-
// tags:
|
926 |
-
// protected
|
927 |
-
|
928 |
-
var c = (e.keyChar && e.keyChar.toLowerCase()) || e.keyCode,
|
929 |
-
handlers = this._keyHandlers[c],
|
930 |
-
args = arguments;
|
931 |
-
|
932 |
-
if(handlers && !e.altKey){
|
933 |
-
dojo.some(handlers, function(h){
|
934 |
-
// treat meta- same as ctrl-, for benefit of mac users
|
935 |
-
if(!(h.shift ^ e.shiftKey) && !(h.ctrl ^ (e.ctrlKey||e.metaKey))){
|
936 |
-
if(!h.handler.apply(this, args)){
|
937 |
-
e.preventDefault();
|
938 |
-
}
|
939 |
-
return true;
|
940 |
-
}
|
941 |
-
}, this);
|
942 |
-
}
|
943 |
-
|
944 |
-
// function call after the character has been inserted
|
945 |
-
if(!this._onKeyHitch){
|
946 |
-
this._onKeyHitch = dojo.hitch(this, "onKeyPressed");
|
947 |
-
}
|
948 |
-
setTimeout(this._onKeyHitch, 1);
|
949 |
-
return true;
|
950 |
-
},
|
951 |
-
|
952 |
-
addKeyHandler: function(/*String*/ key, /*Boolean*/ ctrl, /*Boolean*/ shift, /*Function*/ handler){
|
953 |
-
// summary:
|
954 |
-
// Add a handler for a keyboard shortcut
|
955 |
-
// description:
|
956 |
-
// The key argument should be in lowercase if it is a letter character
|
957 |
-
// tags:
|
958 |
-
// protected
|
959 |
-
if(!dojo.isArray(this._keyHandlers[key])){
|
960 |
-
this._keyHandlers[key] = [];
|
961 |
-
}
|
962 |
-
//TODO: would be nice to make this a hash instead of an array for quick lookups
|
963 |
-
this._keyHandlers[key].push({
|
964 |
-
shift: shift || false,
|
965 |
-
ctrl: ctrl || false,
|
966 |
-
handler: handler
|
967 |
-
});
|
968 |
-
},
|
969 |
-
|
970 |
-
onKeyPressed: function(){
|
971 |
-
// summary:
|
972 |
-
// Handler for after the user has pressed a key, and the display has been updated.
|
973 |
-
// (Runs on a timer so that it runs after the display is updated)
|
974 |
-
// tags:
|
975 |
-
// private
|
976 |
-
this.onDisplayChanged(/*e*/); // can't pass in e
|
977 |
-
},
|
978 |
-
|
979 |
-
onClick: function(/*Event*/ e){
|
980 |
-
// summary:
|
981 |
-
// Handler for when the user clicks.
|
982 |
-
// tags:
|
983 |
-
// private
|
984 |
-
|
985 |
-
// console.info('onClick',this._tryDesignModeOn);
|
986 |
-
this.onDisplayChanged(e);
|
987 |
-
},
|
988 |
-
|
989 |
-
_onIEMouseDown: function(/*Event*/ e){
|
990 |
-
// summary:
|
991 |
-
// IE only to prevent 2 clicks to focus
|
992 |
-
// tags:
|
993 |
-
// protected
|
994 |
-
|
995 |
-
if(!this._focused && !this.disabled){
|
996 |
-
this.focus();
|
997 |
-
}
|
998 |
-
},
|
999 |
-
|
1000 |
-
_onBlur: function(e){
|
1001 |
-
// summary:
|
1002 |
-
// Called from focus manager when focus has moved away from this editor
|
1003 |
-
// tags:
|
1004 |
-
// protected
|
1005 |
-
|
1006 |
-
// console.info('_onBlur')
|
1007 |
-
|
1008 |
-
this.inherited(arguments);
|
1009 |
-
|
1010 |
-
var newValue = this.getValue(true);
|
1011 |
-
if(newValue != this.value){
|
1012 |
-
this.onChange(newValue);
|
1013 |
-
}
|
1014 |
-
this._set("value", newValue);
|
1015 |
-
},
|
1016 |
-
|
1017 |
-
_onFocus: function(/*Event*/ e){
|
1018 |
-
// summary:
|
1019 |
-
// Called from focus manager when focus has moved into this editor
|
1020 |
-
// tags:
|
1021 |
-
// protected
|
1022 |
-
|
1023 |
-
// console.info('_onFocus')
|
1024 |
-
if(!this.disabled){
|
1025 |
-
if(!this._disabledOK){
|
1026 |
-
this.set('disabled', false);
|
1027 |
-
}
|
1028 |
-
this.inherited(arguments);
|
1029 |
-
}
|
1030 |
-
},
|
1031 |
-
|
1032 |
-
// TODO: remove in 2.0
|
1033 |
-
blur: function(){
|
1034 |
-
// summary:
|
1035 |
-
// Remove focus from this instance.
|
1036 |
-
// tags:
|
1037 |
-
// deprecated
|
1038 |
-
if(!dojo.isIE && this.window.document.documentElement && this.window.document.documentElement.focus){
|
1039 |
-
this.window.document.documentElement.focus();
|
1040 |
-
}else if(dojo.doc.body.focus){
|
1041 |
-
dojo.doc.body.focus();
|
1042 |
-
}
|
1043 |
-
},
|
1044 |
-
|
1045 |
-
focus: function(){
|
1046 |
-
// summary:
|
1047 |
-
// Move focus to this editor
|
1048 |
-
if(!this.isLoaded){
|
1049 |
-
this.focusOnLoad = true;
|
1050 |
-
return;
|
1051 |
-
}
|
1052 |
-
if(this._cursorToStart){
|
1053 |
-
delete this._cursorToStart;
|
1054 |
-
if(this.editNode.childNodes){
|
1055 |
-
this.placeCursorAtStart(); // this calls focus() so return
|
1056 |
-
return;
|
1057 |
-
}
|
1058 |
-
}
|
1059 |
-
if(!dojo.isIE){
|
1060 |
-
dijit.focus(this.iframe);
|
1061 |
-
}else if(this.editNode && this.editNode.focus){
|
1062 |
-
// editNode may be hidden in display:none div, lets just punt in this case
|
1063 |
-
//this.editNode.focus(); -> causes IE to scroll always (strict and quirks mode) to the top the Iframe
|
1064 |
-
// if we fire the event manually and let the browser handle the focusing, the latest
|
1065 |
-
// cursor position is focused like in FF
|
1066 |
-
this.iframe.fireEvent('onfocus', document.createEventObject()); // createEventObject only in IE
|
1067 |
-
// }else{
|
1068 |
-
// TODO: should we throw here?
|
1069 |
-
// console.debug("Have no idea how to focus into the editor!");
|
1070 |
-
}
|
1071 |
-
},
|
1072 |
-
|
1073 |
-
// _lastUpdate: 0,
|
1074 |
-
updateInterval: 200,
|
1075 |
-
_updateTimer: null,
|
1076 |
-
onDisplayChanged: function(/*Event*/ e){
|
1077 |
-
// summary:
|
1078 |
-
// This event will be fired everytime the display context
|
1079 |
-
// changes and the result needs to be reflected in the UI.
|
1080 |
-
// description:
|
1081 |
-
// If you don't want to have update too often,
|
1082 |
-
// onNormalizedDisplayChanged should be used instead
|
1083 |
-
// tags:
|
1084 |
-
// private
|
1085 |
-
|
1086 |
-
// var _t=new Date();
|
1087 |
-
if(this._updateTimer){
|
1088 |
-
clearTimeout(this._updateTimer);
|
1089 |
-
}
|
1090 |
-
if(!this._updateHandler){
|
1091 |
-
this._updateHandler = dojo.hitch(this,"onNormalizedDisplayChanged");
|
1092 |
-
}
|
1093 |
-
this._updateTimer = setTimeout(this._updateHandler, this.updateInterval);
|
1094 |
-
|
1095 |
-
// Technically this should trigger a call to watch("value", ...) registered handlers,
|
1096 |
-
// but getValue() is too slow to call on every keystroke so we don't.
|
1097 |
-
},
|
1098 |
-
onNormalizedDisplayChanged: function(){
|
1099 |
-
// summary:
|
1100 |
-
// This event is fired every updateInterval ms or more
|
1101 |
-
// description:
|
1102 |
-
// If something needs to happen immediately after a
|
1103 |
-
// user change, please use onDisplayChanged instead.
|
1104 |
-
// tags:
|
1105 |
-
// private
|
1106 |
-
delete this._updateTimer;
|
1107 |
-
},
|
1108 |
-
onChange: function(newContent){
|
1109 |
-
// summary:
|
1110 |
-
// This is fired if and only if the editor loses focus and
|
1111 |
-
// the content is changed.
|
1112 |
-
},
|
1113 |
-
_normalizeCommand: function(/*String*/ cmd, /*Anything?*/argument){
|
1114 |
-
// summary:
|
1115 |
-
// Used as the advice function by dojo.connect to map our
|
1116 |
-
// normalized set of commands to those supported by the target
|
1117 |
-
// browser.
|
1118 |
-
// tags:
|
1119 |
-
// private
|
1120 |
-
|
1121 |
-
var command = cmd.toLowerCase();
|
1122 |
-
if(command == "formatblock"){
|
1123 |
-
if(dojo.isSafari && argument === undefined){ command = "heading"; }
|
1124 |
-
}else if(command == "hilitecolor" && !dojo.isMoz){
|
1125 |
-
command = "backcolor";
|
1126 |
-
}
|
1127 |
-
|
1128 |
-
return command;
|
1129 |
-
},
|
1130 |
-
|
1131 |
-
_qcaCache: {},
|
1132 |
-
queryCommandAvailable: function(/*String*/ command){
|
1133 |
-
// summary:
|
1134 |
-
// Tests whether a command is supported by the host. Clients
|
1135 |
-
// SHOULD check whether a command is supported before attempting
|
1136 |
-
// to use it, behaviour for unsupported commands is undefined.
|
1137 |
-
// command:
|
1138 |
-
// The command to test for
|
1139 |
-
// tags:
|
1140 |
-
// private
|
1141 |
-
|
1142 |
-
// memoizing version. See _queryCommandAvailable for computing version
|
1143 |
-
var ca = this._qcaCache[command];
|
1144 |
-
if(ca !== undefined){ return ca; }
|
1145 |
-
return (this._qcaCache[command] = this._queryCommandAvailable(command));
|
1146 |
-
},
|
1147 |
-
|
1148 |
-
_queryCommandAvailable: function(/*String*/ command){
|
1149 |
-
// summary:
|
1150 |
-
// See queryCommandAvailable().
|
1151 |
-
// tags:
|
1152 |
-
// private
|
1153 |
-
|
1154 |
-
var ie = 1;
|
1155 |
-
var mozilla = 1 << 1;
|
1156 |
-
var webkit = 1 << 2;
|
1157 |
-
var opera = 1 << 3;
|
1158 |
-
|
1159 |
-
function isSupportedBy(browsers){
|
1160 |
-
return {
|
1161 |
-
ie: Boolean(browsers & ie),
|
1162 |
-
mozilla: Boolean(browsers & mozilla),
|
1163 |
-
webkit: Boolean(browsers & webkit),
|
1164 |
-
opera: Boolean(browsers & opera)
|
1165 |
-
};
|
1166 |
-
}
|
1167 |
-
|
1168 |
-
var supportedBy = null;
|
1169 |
-
|
1170 |
-
switch(command.toLowerCase()){
|
1171 |
-
case "bold": case "italic": case "underline":
|
1172 |
-
case "subscript": case "superscript":
|
1173 |
-
case "fontname": case "fontsize":
|
1174 |
-
case "forecolor": case "hilitecolor":
|
1175 |
-
case "justifycenter": case "justifyfull": case "justifyleft":
|
1176 |
-
case "justifyright": case "delete": case "selectall": case "toggledir":
|
1177 |
-
supportedBy = isSupportedBy(mozilla | ie | webkit | opera);
|
1178 |
-
break;
|
1179 |
-
|
1180 |
-
case "createlink": case "unlink": case "removeformat":
|
1181 |
-
case "inserthorizontalrule": case "insertimage":
|
1182 |
-
case "insertorderedlist": case "insertunorderedlist":
|
1183 |
-
case "indent": case "outdent": case "formatblock":
|
1184 |
-
case "inserthtml": case "undo": case "redo": case "strikethrough": case "tabindent":
|
1185 |
-
supportedBy = isSupportedBy(mozilla | ie | opera | webkit);
|
1186 |
-
break;
|
1187 |
-
|
1188 |
-
case "blockdirltr": case "blockdirrtl":
|
1189 |
-
case "dirltr": case "dirrtl":
|
1190 |
-
case "inlinedirltr": case "inlinedirrtl":
|
1191 |
-
supportedBy = isSupportedBy(ie);
|
1192 |
-
break;
|
1193 |
-
case "cut": case "copy": case "paste":
|
1194 |
-
supportedBy = isSupportedBy( ie | mozilla | webkit);
|
1195 |
-
break;
|
1196 |
-
|
1197 |
-
case "inserttable":
|
1198 |
-
supportedBy = isSupportedBy(mozilla | ie);
|
1199 |
-
break;
|
1200 |
-
|
1201 |
-
case "insertcell": case "insertcol": case "insertrow":
|
1202 |
-
case "deletecells": case "deletecols": case "deleterows":
|
1203 |
-
case "mergecells": case "splitcell":
|
1204 |
-
supportedBy = isSupportedBy(ie | mozilla);
|
1205 |
-
break;
|
1206 |
-
|
1207 |
-
default: return false;
|
1208 |
-
}
|
1209 |
-
|
1210 |
-
return (dojo.isIE && supportedBy.ie) ||
|
1211 |
-
(dojo.isMoz && supportedBy.mozilla) ||
|
1212 |
-
(dojo.isWebKit && supportedBy.webkit) ||
|
1213 |
-
(dojo.isOpera && supportedBy.opera); // Boolean return true if the command is supported, false otherwise
|
1214 |
-
},
|
1215 |
-
|
1216 |
-
execCommand: function(/*String*/ command, argument){
|
1217 |
-
// summary:
|
1218 |
-
// Executes a command in the Rich Text area
|
1219 |
-
// command:
|
1220 |
-
// The command to execute
|
1221 |
-
// argument:
|
1222 |
-
// An optional argument to the command
|
1223 |
-
// tags:
|
1224 |
-
// protected
|
1225 |
-
var returnValue;
|
1226 |
-
|
1227 |
-
//focus() is required for IE to work
|
1228 |
-
//In addition, focus() makes sure after the execution of
|
1229 |
-
//the command, the editor receives the focus as expected
|
1230 |
-
this.focus();
|
1231 |
-
|
1232 |
-
command = this._normalizeCommand(command, argument);
|
1233 |
-
|
1234 |
-
if(argument !== undefined){
|
1235 |
-
if(command == "heading"){
|
1236 |
-
throw new Error("unimplemented");
|
1237 |
-
}else if((command == "formatblock") && dojo.isIE){
|
1238 |
-
argument = '<'+argument+'>';
|
1239 |
-
}
|
1240 |
-
}
|
1241 |
-
|
1242 |
-
//Check to see if we have any over-rides for commands, they will be functions on this
|
1243 |
-
//widget of the form _commandImpl. If we don't, fall through to the basic native
|
1244 |
-
//exec command of the browser.
|
1245 |
-
var implFunc = "_" + command + "Impl";
|
1246 |
-
if(this[implFunc]){
|
1247 |
-
returnValue = this[implFunc](argument);
|
1248 |
-
}else{
|
1249 |
-
argument = arguments.length > 1 ? argument : null;
|
1250 |
-
if(argument || command!="createlink"){
|
1251 |
-
returnValue = this.document.execCommand(command, false, argument);
|
1252 |
-
}
|
1253 |
-
}
|
1254 |
-
|
1255 |
-
this.onDisplayChanged();
|
1256 |
-
return returnValue;
|
1257 |
-
},
|
1258 |
-
|
1259 |
-
queryCommandEnabled: function(/*String*/ command){
|
1260 |
-
// summary:
|
1261 |
-
// Check whether a command is enabled or not.
|
1262 |
-
// tags:
|
1263 |
-
// protected
|
1264 |
-
if(this.disabled || !this._disabledOK){ return false; }
|
1265 |
-
command = this._normalizeCommand(command);
|
1266 |
-
if(dojo.isMoz || dojo.isWebKit){
|
1267 |
-
if(command == "unlink"){ // mozilla returns true always
|
1268 |
-
// console.debug(this._sCall("hasAncestorElement", ['a']));
|
1269 |
-
return this._sCall("hasAncestorElement", ["a"]);
|
1270 |
-
}else if(command == "inserttable"){
|
1271 |
-
return true;
|
1272 |
-
}
|
1273 |
-
}
|
1274 |
-
//see #4109
|
1275 |
-
if(dojo.isWebKit){
|
1276 |
-
if(command == "cut" || command == "copy") {
|
1277 |
-
// WebKit deems clipboard activity as a security threat and natively would return false
|
1278 |
-
var sel = this.window.getSelection();
|
1279 |
-
if(sel){ sel = sel.toString(); }
|
1280 |
-
return !!sel;
|
1281 |
-
}else if(command == "paste"){
|
1282 |
-
return true;
|
1283 |
-
}
|
1284 |
-
}
|
1285 |
-
|
1286 |
-
var elem = dojo.isIE ? this.document.selection.createRange() : this.document;
|
1287 |
-
try{
|
1288 |
-
return elem.queryCommandEnabled(command);
|
1289 |
-
}catch(e){
|
1290 |
-
//Squelch, occurs if editor is hidden on FF 3 (and maybe others.)
|
1291 |
-
return false;
|
1292 |
-
}
|
1293 |
-
|
1294 |
-
},
|
1295 |
-
|
1296 |
-
queryCommandState: function(command){
|
1297 |
-
// summary:
|
1298 |
-
// Check the state of a given command and returns true or false.
|
1299 |
-
// tags:
|
1300 |
-
// protected
|
1301 |
-
|
1302 |
-
if(this.disabled || !this._disabledOK){ return false; }
|
1303 |
-
command = this._normalizeCommand(command);
|
1304 |
-
try{
|
1305 |
-
return this.document.queryCommandState(command);
|
1306 |
-
}catch(e){
|
1307 |
-
//Squelch, occurs if editor is hidden on FF 3 (and maybe others.)
|
1308 |
-
return false;
|
1309 |
-
}
|
1310 |
-
},
|
1311 |
-
|
1312 |
-
queryCommandValue: function(command){
|
1313 |
-
// summary:
|
1314 |
-
// Check the value of a given command. This matters most for
|
1315 |
-
// custom selections and complex values like font value setting.
|
1316 |
-
// tags:
|
1317 |
-
// protected
|
1318 |
-
|
1319 |
-
if(this.disabled || !this._disabledOK){ return false; }
|
1320 |
-
var r;
|
1321 |
-
command = this._normalizeCommand(command);
|
1322 |
-
if(dojo.isIE && command == "formatblock"){
|
1323 |
-
r = this._native2LocalFormatNames[this.document.queryCommandValue(command)];
|
1324 |
-
}else if(dojo.isMoz && command === "hilitecolor"){
|
1325 |
-
var oldValue;
|
1326 |
-
try{
|
1327 |
-
oldValue = this.document.queryCommandValue("styleWithCSS");
|
1328 |
-
}catch(e){
|
1329 |
-
oldValue = false;
|
1330 |
-
}
|
1331 |
-
this.document.execCommand("styleWithCSS", false, true);
|
1332 |
-
r = this.document.queryCommandValue(command);
|
1333 |
-
this.document.execCommand("styleWithCSS", false, oldValue);
|
1334 |
-
}else{
|
1335 |
-
r = this.document.queryCommandValue(command);
|
1336 |
-
}
|
1337 |
-
return r;
|
1338 |
-
},
|
1339 |
-
|
1340 |
-
// Misc.
|
1341 |
-
|
1342 |
-
_sCall: function(name, args){
|
1343 |
-
// summary:
|
1344 |
-
// Run the named method of dijit._editor.selection over the
|
1345 |
-
// current editor instance's window, with the passed args.
|
1346 |
-
// tags:
|
1347 |
-
// private
|
1348 |
-
return dojo.withGlobal(this.window, name, dijit._editor.selection, args);
|
1349 |
-
},
|
1350 |
-
|
1351 |
-
// FIXME: this is a TON of code duplication. Why?
|
1352 |
-
|
1353 |
-
placeCursorAtStart: function(){
|
1354 |
-
// summary:
|
1355 |
-
// Place the cursor at the start of the editing area.
|
1356 |
-
// tags:
|
1357 |
-
// private
|
1358 |
-
|
1359 |
-
this.focus();
|
1360 |
-
|
1361 |
-
//see comments in placeCursorAtEnd
|
1362 |
-
var isvalid=false;
|
1363 |
-
if(dojo.isMoz){
|
1364 |
-
// TODO: Is this branch even necessary?
|
1365 |
-
var first=this.editNode.firstChild;
|
1366 |
-
while(first){
|
1367 |
-
if(first.nodeType == 3){
|
1368 |
-
if(first.nodeValue.replace(/^\s+|\s+$/g, "").length>0){
|
1369 |
-
isvalid=true;
|
1370 |
-
this._sCall("selectElement", [ first ]);
|
1371 |
-
break;
|
1372 |
-
}
|
1373 |
-
}else if(first.nodeType == 1){
|
1374 |
-
isvalid=true;
|
1375 |
-
var tg = first.tagName ? first.tagName.toLowerCase() : "";
|
1376 |
-
// Collapse before childless tags.
|
1377 |
-
if(/br|input|img|base|meta|area|basefont|hr|link/.test(tg)){
|
1378 |
-
this._sCall("selectElement", [ first ]);
|
1379 |
-
}else{
|
1380 |
-
// Collapse inside tags with children.
|
1381 |
-
this._sCall("selectElementChildren", [ first ]);
|
1382 |
-
}
|
1383 |
-
break;
|
1384 |
-
}
|
1385 |
-
first = first.nextSibling;
|
1386 |
-
}
|
1387 |
-
}else{
|
1388 |
-
isvalid=true;
|
1389 |
-
this._sCall("selectElementChildren", [ this.editNode ]);
|
1390 |
-
}
|
1391 |
-
if(isvalid){
|
1392 |
-
this._sCall("collapse", [ true ]);
|
1393 |
-
}
|
1394 |
-
},
|
1395 |
-
|
1396 |
-
placeCursorAtEnd: function(){
|
1397 |
-
// summary:
|
1398 |
-
// Place the cursor at the end of the editing area.
|
1399 |
-
// tags:
|
1400 |
-
// private
|
1401 |
-
|
1402 |
-
this.focus();
|
1403 |
-
|
1404 |
-
//In mozilla, if last child is not a text node, we have to use
|
1405 |
-
// selectElementChildren on this.editNode.lastChild otherwise the
|
1406 |
-
// cursor would be placed at the end of the closing tag of
|
1407 |
-
//this.editNode.lastChild
|
1408 |
-
var isvalid=false;
|
1409 |
-
if(dojo.isMoz){
|
1410 |
-
var last=this.editNode.lastChild;
|
1411 |
-
while(last){
|
1412 |
-
if(last.nodeType == 3){
|
1413 |
-
if(last.nodeValue.replace(/^\s+|\s+$/g, "").length>0){
|
1414 |
-
isvalid=true;
|
1415 |
-
this._sCall("selectElement", [ last ]);
|
1416 |
-
break;
|
1417 |
-
}
|
1418 |
-
}else if(last.nodeType == 1){
|
1419 |
-
isvalid=true;
|
1420 |
-
if(last.lastChild){
|
1421 |
-
this._sCall("selectElement", [ last.lastChild ]);
|
1422 |
-
}else{
|
1423 |
-
this._sCall("selectElement", [ last ]);
|
1424 |
-
}
|
1425 |
-
break;
|
1426 |
-
}
|
1427 |
-
last = last.previousSibling;
|
1428 |
-
}
|
1429 |
-
}else{
|
1430 |
-
isvalid=true;
|
1431 |
-
this._sCall("selectElementChildren", [ this.editNode ]);
|
1432 |
-
}
|
1433 |
-
if(isvalid){
|
1434 |
-
this._sCall("collapse", [ false ]);
|
1435 |
-
}
|
1436 |
-
},
|
1437 |
-
|
1438 |
-
getValue: function(/*Boolean?*/ nonDestructive){
|
1439 |
-
// summary:
|
1440 |
-
// Return the current content of the editing area (post filters
|
1441 |
-
// are applied). Users should call get('value') instead.
|
1442 |
-
// nonDestructive:
|
1443 |
-
// defaults to false. Should the post-filtering be run over a copy
|
1444 |
-
// of the live DOM? Most users should pass "true" here unless they
|
1445 |
-
// *really* know that none of the installed filters are going to
|
1446 |
-
// mess up the editing session.
|
1447 |
-
// tags:
|
1448 |
-
// private
|
1449 |
-
if(this.textarea){
|
1450 |
-
if(this.isClosed || !this.isLoaded){
|
1451 |
-
return this.textarea.value;
|
1452 |
-
}
|
1453 |
-
}
|
1454 |
-
|
1455 |
-
return this._postFilterContent(null, nonDestructive);
|
1456 |
-
},
|
1457 |
-
_getValueAttr: function(){
|
1458 |
-
// summary:
|
1459 |
-
// Hook to make attr("value") work
|
1460 |
-
return this.getValue(true);
|
1461 |
-
},
|
1462 |
-
|
1463 |
-
setValue: function(/*String*/ html){
|
1464 |
-
// summary:
|
1465 |
-
// This function sets the content. No undo history is preserved.
|
1466 |
-
// Users should use set('value', ...) instead.
|
1467 |
-
// tags:
|
1468 |
-
// deprecated
|
1469 |
-
|
1470 |
-
// TODO: remove this and getValue() for 2.0, and move code to _setValueAttr()
|
1471 |
-
|
1472 |
-
if(!this.isLoaded){
|
1473 |
-
// try again after the editor is finished loading
|
1474 |
-
this.onLoadDeferred.addCallback(dojo.hitch(this, function(){
|
1475 |
-
this.setValue(html);
|
1476 |
-
}));
|
1477 |
-
return;
|
1478 |
-
}
|
1479 |
-
this._cursorToStart = true;
|
1480 |
-
if(this.textarea && (this.isClosed || !this.isLoaded)){
|
1481 |
-
this.textarea.value=html;
|
1482 |
-
}else{
|
1483 |
-
html = this._preFilterContent(html);
|
1484 |
-
var node = this.isClosed ? this.domNode : this.editNode;
|
1485 |
-
if(html && dojo.isMoz && html.toLowerCase() == "<p></p>"){
|
1486 |
-
html = "<p> </p>";
|
1487 |
-
}
|
1488 |
-
|
1489 |
-
// Use to avoid webkit problems where editor is disabled until the user clicks it
|
1490 |
-
if(!html && dojo.isWebKit){
|
1491 |
-
html = " ";
|
1492 |
-
}
|
1493 |
-
node.innerHTML = html;
|
1494 |
-
this._preDomFilterContent(node);
|
1495 |
-
}
|
1496 |
-
|
1497 |
-
this.onDisplayChanged();
|
1498 |
-
this._set("value", this.getValue(true));
|
1499 |
-
},
|
1500 |
-
|
1501 |
-
replaceValue: function(/*String*/ html){
|
1502 |
-
// summary:
|
1503 |
-
// This function set the content while trying to maintain the undo stack
|
1504 |
-
// (now only works fine with Moz, this is identical to setValue in all
|
1505 |
-
// other browsers)
|
1506 |
-
// tags:
|
1507 |
-
// protected
|
1508 |
-
|
1509 |
-
if(this.isClosed){
|
1510 |
-
this.setValue(html);
|
1511 |
-
}else if(this.window && this.window.getSelection && !dojo.isMoz){ // Safari
|
1512 |
-
// look ma! it's a totally f'd browser!
|
1513 |
-
this.setValue(html);
|
1514 |
-
}else if(this.window && this.window.getSelection){ // Moz
|
1515 |
-
html = this._preFilterContent(html);
|
1516 |
-
this.execCommand("selectall");
|
1517 |
-
if(!html){
|
1518 |
-
this._cursorToStart = true;
|
1519 |
-
html = " ";
|
1520 |
-
}
|
1521 |
-
this.execCommand("inserthtml", html);
|
1522 |
-
this._preDomFilterContent(this.editNode);
|
1523 |
-
}else if(this.document && this.document.selection){//IE
|
1524 |
-
//In IE, when the first element is not a text node, say
|
1525 |
-
//an <a> tag, when replacing the content of the editing
|
1526 |
-
//area, the <a> tag will be around all the content
|
1527 |
-
//so for now, use setValue for IE too
|
1528 |
-
this.setValue(html);
|
1529 |
-
}
|
1530 |
-
|
1531 |
-
this._set("value", this.getValue(true));
|
1532 |
-
},
|
1533 |
-
|
1534 |
-
_preFilterContent: function(/*String*/ html){
|
1535 |
-
// summary:
|
1536 |
-
// Filter the input before setting the content of the editing
|
1537 |
-
// area. DOM pre-filtering may happen after this
|
1538 |
-
// string-based filtering takes place but as of 1.2, this is not
|
1539 |
-
// guaranteed for operations such as the inserthtml command.
|
1540 |
-
// tags:
|
1541 |
-
// private
|
1542 |
-
|
1543 |
-
var ec = html;
|
1544 |
-
dojo.forEach(this.contentPreFilters, function(ef){ if(ef){ ec = ef(ec); } });
|
1545 |
-
return ec;
|
1546 |
-
},
|
1547 |
-
_preDomFilterContent: function(/*DomNode*/ dom){
|
1548 |
-
// summary:
|
1549 |
-
// filter the input's live DOM. All filter operations should be
|
1550 |
-
// considered to be "live" and operating on the DOM that the user
|
1551 |
-
// will be interacting with in their editing session.
|
1552 |
-
// tags:
|
1553 |
-
// private
|
1554 |
-
dom = dom || this.editNode;
|
1555 |
-
dojo.forEach(this.contentDomPreFilters, function(ef){
|
1556 |
-
if(ef && dojo.isFunction(ef)){
|
1557 |
-
ef(dom);
|
1558 |
-
}
|
1559 |
-
}, this);
|
1560 |
-
},
|
1561 |
-
|
1562 |
-
_postFilterContent: function(
|
1563 |
-
/*DomNode|DomNode[]|String?*/ dom,
|
1564 |
-
/*Boolean?*/ nonDestructive){
|
1565 |
-
// summary:
|
1566 |
-
// filter the output after getting the content of the editing area
|
1567 |
-
//
|
1568 |
-
// description:
|
1569 |
-
// post-filtering allows plug-ins and users to specify any number
|
1570 |
-
// of transforms over the editor's content, enabling many common
|
1571 |
-
// use-cases such as transforming absolute to relative URLs (and
|
1572 |
-
// vice-versa), ensuring conformance with a particular DTD, etc.
|
1573 |
-
// The filters are registered in the contentDomPostFilters and
|
1574 |
-
// contentPostFilters arrays. Each item in the
|
1575 |
-
// contentDomPostFilters array is a function which takes a DOM
|
1576 |
-
// Node or array of nodes as its only argument and returns the
|
1577 |
-
// same. It is then passed down the chain for further filtering.
|
1578 |
-
// The contentPostFilters array behaves the same way, except each
|
1579 |
-
// member operates on strings. Together, the DOM and string-based
|
1580 |
-
// filtering allow the full range of post-processing that should
|
1581 |
-
// be necessaray to enable even the most agressive of post-editing
|
1582 |
-
// conversions to take place.
|
1583 |
-
//
|
1584 |
-
// If nonDestructive is set to "true", the nodes are cloned before
|
1585 |
-
// filtering proceeds to avoid potentially destructive transforms
|
1586 |
-
// to the content which may still needed to be edited further.
|
1587 |
-
// Once DOM filtering has taken place, the serialized version of
|
1588 |
-
// the DOM which is passed is run through each of the
|
1589 |
-
// contentPostFilters functions.
|
1590 |
-
//
|
1591 |
-
// dom:
|
1592 |
-
// a node, set of nodes, which to filter using each of the current
|
1593 |
-
// members of the contentDomPostFilters and contentPostFilters arrays.
|
1594 |
-
//
|
1595 |
-
// nonDestructive:
|
1596 |
-
// defaults to "false". If true, ensures that filtering happens on
|
1597 |
-
// a clone of the passed-in content and not the actual node
|
1598 |
-
// itself.
|
1599 |
-
//
|
1600 |
-
// tags:
|
1601 |
-
// private
|
1602 |
-
|
1603 |
-
var ec;
|
1604 |
-
if(!dojo.isString(dom)){
|
1605 |
-
dom = dom || this.editNode;
|
1606 |
-
if(this.contentDomPostFilters.length){
|
1607 |
-
if(nonDestructive){
|
1608 |
-
dom = dojo.clone(dom);
|
1609 |
-
}
|
1610 |
-
dojo.forEach(this.contentDomPostFilters, function(ef){
|
1611 |
-
dom = ef(dom);
|
1612 |
-
});
|
1613 |
-
}
|
1614 |
-
ec = dijit._editor.getChildrenHtml(dom);
|
1615 |
-
}else{
|
1616 |
-
ec = dom;
|
1617 |
-
}
|
1618 |
-
|
1619 |
-
if(!dojo.trim(ec.replace(/^\xA0\xA0*/, '').replace(/\xA0\xA0*$/, '')).length){
|
1620 |
-
ec = "";
|
1621 |
-
}
|
1622 |
-
|
1623 |
-
// if(dojo.isIE){
|
1624 |
-
// //removing appended <P> </P> for IE
|
1625 |
-
// ec = ec.replace(/(?:<p> </p>[\n\r]*)+$/i,"");
|
1626 |
-
// }
|
1627 |
-
dojo.forEach(this.contentPostFilters, function(ef){
|
1628 |
-
ec = ef(ec);
|
1629 |
-
});
|
1630 |
-
|
1631 |
-
return ec;
|
1632 |
-
},
|
1633 |
-
|
1634 |
-
_saveContent: function(/*Event*/ e){
|
1635 |
-
// summary:
|
1636 |
-
// Saves the content in an onunload event if the editor has not been closed
|
1637 |
-
// tags:
|
1638 |
-
// private
|
1639 |
-
|
1640 |
-
var saveTextarea = dojo.byId(dijit._scopeName + "._editor.RichText.value");
|
1641 |
-
if(saveTextarea.value){
|
1642 |
-
saveTextarea.value += this._SEPARATOR;
|
1643 |
-
}
|
1644 |
-
saveTextarea.value += this.name + this._NAME_CONTENT_SEP + this.getValue(true);
|
1645 |
-
},
|
1646 |
-
|
1647 |
-
|
1648 |
-
escapeXml: function(/*String*/ str, /*Boolean*/ noSingleQuotes){
|
1649 |
-
// summary:
|
1650 |
-
// Adds escape sequences for special characters in XML.
|
1651 |
-
// Optionally skips escapes for single quotes
|
1652 |
-
// tags:
|
1653 |
-
// private
|
1654 |
-
|
1655 |
-
str = str.replace(/&/gm, "&").replace(/</gm, "<").replace(/>/gm, ">").replace(/"/gm, """);
|
1656 |
-
if(!noSingleQuotes){
|
1657 |
-
str = str.replace(/'/gm, "'");
|
1658 |
-
}
|
1659 |
-
return str; // string
|
1660 |
-
},
|
1661 |
-
|
1662 |
-
getNodeHtml: function(/* DomNode */ node){
|
1663 |
-
// summary:
|
1664 |
-
// Deprecated. Use dijit._editor._getNodeHtml() instead.
|
1665 |
-
// tags:
|
1666 |
-
// deprecated
|
1667 |
-
dojo.deprecated('dijit.Editor::getNodeHtml is deprecated','use dijit._editor.getNodeHtml instead', 2);
|
1668 |
-
return dijit._editor.getNodeHtml(node); // String
|
1669 |
-
},
|
1670 |
-
|
1671 |
-
getNodeChildrenHtml: function(/* DomNode */ dom){
|
1672 |
-
// summary:
|
1673 |
-
// Deprecated. Use dijit._editor.getChildrenHtml() instead.
|
1674 |
-
// tags:
|
1675 |
-
// deprecated
|
1676 |
-
dojo.deprecated('dijit.Editor::getNodeChildrenHtml is deprecated','use dijit._editor.getChildrenHtml instead', 2);
|
1677 |
-
return dijit._editor.getChildrenHtml(dom);
|
1678 |
-
},
|
1679 |
-
|
1680 |
-
close: function(/*Boolean?*/ save){
|
1681 |
-
// summary:
|
1682 |
-
// Kills the editor and optionally writes back the modified contents to the
|
1683 |
-
// element from which it originated.
|
1684 |
-
// save:
|
1685 |
-
// Whether or not to save the changes. If false, the changes are discarded.
|
1686 |
-
// tags:
|
1687 |
-
// private
|
1688 |
-
|
1689 |
-
if(this.isClosed){ return; }
|
1690 |
-
|
1691 |
-
if(!arguments.length){ save = true; }
|
1692 |
-
if(save){
|
1693 |
-
this._set("value", this.getValue(true));
|
1694 |
-
}
|
1695 |
-
|
1696 |
-
// line height is squashed for iframes
|
1697 |
-
// FIXME: why was this here? if (this.iframe){ this.domNode.style.lineHeight = null; }
|
1698 |
-
|
1699 |
-
if(this.interval){ clearInterval(this.interval); }
|
1700 |
-
|
1701 |
-
if(this._webkitListener){
|
1702 |
-
//Cleaup of WebKit fix: #9532
|
1703 |
-
this.disconnect(this._webkitListener);
|
1704 |
-
delete this._webkitListener;
|
1705 |
-
}
|
1706 |
-
|
1707 |
-
// Guard against memory leaks on IE (see #9268)
|
1708 |
-
if(dojo.isIE){
|
1709 |
-
this.iframe.onfocus = null;
|
1710 |
-
}
|
1711 |
-
this.iframe._loadFunc = null;
|
1712 |
-
|
1713 |
-
if(this._iframeRegHandle){
|
1714 |
-
dijit.unregisterIframe(this._iframeRegHandle);
|
1715 |
-
delete this._iframeRegHandle;
|
1716 |
-
}
|
1717 |
-
|
1718 |
-
if(this.textarea){
|
1719 |
-
var s = this.textarea.style;
|
1720 |
-
s.position = "";
|
1721 |
-
s.left = s.top = "";
|
1722 |
-
if(dojo.isIE){
|
1723 |
-
s.overflow = this.__overflow;
|
1724 |
-
this.__overflow = null;
|
1725 |
-
}
|
1726 |
-
this.textarea.value = this.value;
|
1727 |
-
dojo.destroy(this.domNode);
|
1728 |
-
this.domNode = this.textarea;
|
1729 |
-
}else{
|
1730 |
-
// Note that this destroys the iframe
|
1731 |
-
this.domNode.innerHTML = this.value;
|
1732 |
-
}
|
1733 |
-
delete this.iframe;
|
1734 |
-
|
1735 |
-
dojo.removeClass(this.domNode, this.baseClass);
|
1736 |
-
this.isClosed = true;
|
1737 |
-
this.isLoaded = false;
|
1738 |
-
|
1739 |
-
delete this.editNode;
|
1740 |
-
delete this.focusNode;
|
1741 |
-
|
1742 |
-
if(this.window && this.window._frameElement){
|
1743 |
-
this.window._frameElement = null;
|
1744 |
-
}
|
1745 |
-
|
1746 |
-
this.window = null;
|
1747 |
-
this.document = null;
|
1748 |
-
this.editingArea = null;
|
1749 |
-
this.editorObject = null;
|
1750 |
-
},
|
1751 |
-
|
1752 |
-
destroy: function(){
|
1753 |
-
if(!this.isClosed){ this.close(false); }
|
1754 |
-
this.inherited(arguments);
|
1755 |
-
if(dijit._editor._globalSaveHandler){
|
1756 |
-
delete dijit._editor._globalSaveHandler[this.id];
|
1757 |
-
}
|
1758 |
-
},
|
1759 |
-
|
1760 |
-
_removeMozBogus: function(/* String */ html){
|
1761 |
-
// summary:
|
1762 |
-
// Post filter to remove unwanted HTML attributes generated by mozilla
|
1763 |
-
// tags:
|
1764 |
-
// private
|
1765 |
-
return html.replace(/\stype="_moz"/gi, '').replace(/\s_moz_dirty=""/gi, '').replace(/_moz_resizing="(true|false)"/gi,''); // String
|
1766 |
-
},
|
1767 |
-
_removeWebkitBogus: function(/* String */ html){
|
1768 |
-
// summary:
|
1769 |
-
// Post filter to remove unwanted HTML attributes generated by webkit
|
1770 |
-
// tags:
|
1771 |
-
// private
|
1772 |
-
html = html.replace(/\sclass="webkit-block-placeholder"/gi, '');
|
1773 |
-
html = html.replace(/\sclass="apple-style-span"/gi, '');
|
1774 |
-
// For some reason copy/paste sometime adds extra meta tags for charset on
|
1775 |
-
// webkit (chrome) on mac.They need to be removed. See: #12007"
|
1776 |
-
html = html.replace(/<meta charset=\"utf-8\" \/>/gi, '');
|
1777 |
-
return html; // String
|
1778 |
-
},
|
1779 |
-
_normalizeFontStyle: function(/* String */ html){
|
1780 |
-
// summary:
|
1781 |
-
// Convert 'strong' and 'em' to 'b' and 'i'.
|
1782 |
-
// description:
|
1783 |
-
// Moz can not handle strong/em tags correctly, so to help
|
1784 |
-
// mozilla and also to normalize output, convert them to 'b' and 'i'.
|
1785 |
-
//
|
1786 |
-
// Note the IE generates 'strong' and 'em' rather than 'b' and 'i'
|
1787 |
-
// tags:
|
1788 |
-
// private
|
1789 |
-
return html.replace(/<(\/)?strong([ \>])/gi, '<$1b$2')
|
1790 |
-
.replace(/<(\/)?em([ \>])/gi, '<$1i$2' ); // String
|
1791 |
-
},
|
1792 |
-
|
1793 |
-
_preFixUrlAttributes: function(/* String */ html){
|
1794 |
-
// summary:
|
1795 |
-
// Pre-filter to do fixing to href attributes on <a> and <img> tags
|
1796 |
-
// tags:
|
1797 |
-
// private
|
1798 |
-
return html.replace(/(?:(<a(?=\s).*?\shref=)("|')(.*?)\2)|(?:(<a\s.*?href=)([^"'][^ >]+))/gi,
|
1799 |
-
'$1$4$2$3$5$2 _djrealurl=$2$3$5$2')
|
1800 |
-
.replace(/(?:(<img(?=\s).*?\ssrc=)("|')(.*?)\2)|(?:(<img\s.*?src=)([^"'][^ >]+))/gi,
|
1801 |
-
'$1$4$2$3$5$2 _djrealurl=$2$3$5$2'); // String
|
1802 |
-
},
|
1803 |
-
|
1804 |
-
/*****************************************************************************
|
1805 |
-
The following functions implement HTML manipulation commands for various
|
1806 |
-
browser/contentEditable implementations. The goal of them is to enforce
|
1807 |
-
standard behaviors of them.
|
1808 |
-
******************************************************************************/
|
1809 |
-
|
1810 |
-
_inserthorizontalruleImpl: function(argument){
|
1811 |
-
// summary:
|
1812 |
-
// This function implements the insertion of HTML 'HR' tags.
|
1813 |
-
// into a point on the page. IE doesn't to it right, so
|
1814 |
-
// we have to use an alternate form
|
1815 |
-
// argument:
|
1816 |
-
// arguments to the exec command, if any.
|
1817 |
-
// tags:
|
1818 |
-
// protected
|
1819 |
-
if(dojo.isIE){
|
1820 |
-
return this._inserthtmlImpl("<hr>");
|
1821 |
-
}
|
1822 |
-
return this.document.execCommand("inserthorizontalrule", false, argument);
|
1823 |
-
},
|
1824 |
-
|
1825 |
-
_unlinkImpl: function(argument){
|
1826 |
-
// summary:
|
1827 |
-
// This function implements the unlink of an 'a' tag.
|
1828 |
-
// argument:
|
1829 |
-
// arguments to the exec command, if any.
|
1830 |
-
// tags:
|
1831 |
-
// protected
|
1832 |
-
if((this.queryCommandEnabled("unlink")) && (dojo.isMoz || dojo.isWebKit)){
|
1833 |
-
var a = this._sCall("getAncestorElement", [ "a" ]);
|
1834 |
-
this._sCall("selectElement", [ a ]);
|
1835 |
-
return this.document.execCommand("unlink", false, null);
|
1836 |
-
}
|
1837 |
-
return this.document.execCommand("unlink", false, argument);
|
1838 |
-
},
|
1839 |
-
|
1840 |
-
_hilitecolorImpl: function(argument){
|
1841 |
-
// summary:
|
1842 |
-
// This function implements the hilitecolor command
|
1843 |
-
// argument:
|
1844 |
-
// arguments to the exec command, if any.
|
1845 |
-
// tags:
|
1846 |
-
// protected
|
1847 |
-
var returnValue;
|
1848 |
-
if(dojo.isMoz){
|
1849 |
-
// mozilla doesn't support hilitecolor properly when useCSS is
|
1850 |
-
// set to false (bugzilla #279330)
|
1851 |
-
this.document.execCommand("styleWithCSS", false, true);
|
1852 |
-
returnValue = this.document.execCommand("hilitecolor", false, argument);
|
1853 |
-
this.document.execCommand("styleWithCSS", false, false);
|
1854 |
-
}else{
|
1855 |
-
returnValue = this.document.execCommand("hilitecolor", false, argument);
|
1856 |
-
}
|
1857 |
-
return returnValue;
|
1858 |
-
},
|
1859 |
-
|
1860 |
-
_backcolorImpl: function(argument){
|
1861 |
-
// summary:
|
1862 |
-
// This function implements the backcolor command
|
1863 |
-
// argument:
|
1864 |
-
// arguments to the exec command, if any.
|
1865 |
-
// tags:
|
1866 |
-
// protected
|
1867 |
-
if(dojo.isIE){
|
1868 |
-
// Tested under IE 6 XP2, no problem here, comment out
|
1869 |
-
// IE weirdly collapses ranges when we exec these commands, so prevent it
|
1870 |
-
// var tr = this.document.selection.createRange();
|
1871 |
-
argument = argument ? argument : null;
|
1872 |
-
}
|
1873 |
-
return this.document.execCommand("backcolor", false, argument);
|
1874 |
-
},
|
1875 |
-
|
1876 |
-
_forecolorImpl: function(argument){
|
1877 |
-
// summary:
|
1878 |
-
// This function implements the forecolor command
|
1879 |
-
// argument:
|
1880 |
-
// arguments to the exec command, if any.
|
1881 |
-
// tags:
|
1882 |
-
// protected
|
1883 |
-
if(dojo.isIE){
|
1884 |
-
// Tested under IE 6 XP2, no problem here, comment out
|
1885 |
-
// IE weirdly collapses ranges when we exec these commands, so prevent it
|
1886 |
-
// var tr = this.document.selection.createRange();
|
1887 |
-
argument = argument? argument : null;
|
1888 |
-
}
|
1889 |
-
return this.document.execCommand("forecolor", false, argument);
|
1890 |
-
},
|
1891 |
-
|
1892 |
-
_inserthtmlImpl: function(argument){
|
1893 |
-
// summary:
|
1894 |
-
// This function implements the insertion of HTML content into
|
1895 |
-
// a point on the page.
|
1896 |
-
// argument:
|
1897 |
-
// The content to insert, if any.
|
1898 |
-
// tags:
|
1899 |
-
// protected
|
1900 |
-
argument = this._preFilterContent(argument);
|
1901 |
-
var rv = true;
|
1902 |
-
if(dojo.isIE){
|
1903 |
-
var insertRange = this.document.selection.createRange();
|
1904 |
-
if(this.document.selection.type.toUpperCase() == 'CONTROL'){
|
1905 |
-
var n=insertRange.item(0);
|
1906 |
-
while(insertRange.length){
|
1907 |
-
insertRange.remove(insertRange.item(0));
|
1908 |
-
}
|
1909 |
-
n.outerHTML=argument;
|
1910 |
-
}else{
|
1911 |
-
insertRange.pasteHTML(argument);
|
1912 |
-
}
|
1913 |
-
insertRange.select();
|
1914 |
-
//insertRange.collapse(true);
|
1915 |
-
}else if(dojo.isMoz && !argument.length){
|
1916 |
-
//mozilla can not inserthtml an empty html to delete current selection
|
1917 |
-
//so we delete the selection instead in this case
|
1918 |
-
this._sCall("remove"); // FIXME
|
1919 |
-
}else{
|
1920 |
-
rv = this.document.execCommand("inserthtml", false, argument);
|
1921 |
-
}
|
1922 |
-
return rv;
|
1923 |
-
},
|
1924 |
-
|
1925 |
-
_boldImpl: function(argument){
|
1926 |
-
// summary:
|
1927 |
-
// This function implements an over-ride of the bold command.
|
1928 |
-
// argument:
|
1929 |
-
// Not used, operates by selection.
|
1930 |
-
// tags:
|
1931 |
-
// protected
|
1932 |
-
if(dojo.isIE){
|
1933 |
-
this._adaptIESelection()
|
1934 |
-
}
|
1935 |
-
return this.document.execCommand("bold", false, argument);
|
1936 |
-
},
|
1937 |
-
|
1938 |
-
_italicImpl: function(argument){
|
1939 |
-
// summary:
|
1940 |
-
// This function implements an over-ride of the italic command.
|
1941 |
-
// argument:
|
1942 |
-
// Not used, operates by selection.
|
1943 |
-
// tags:
|
1944 |
-
// protected
|
1945 |
-
if(dojo.isIE){
|
1946 |
-
this._adaptIESelection()
|
1947 |
-
}
|
1948 |
-
return this.document.execCommand("italic", false, argument);
|
1949 |
-
},
|
1950 |
-
|
1951 |
-
_underlineImpl: function(argument){
|
1952 |
-
// summary:
|
1953 |
-
// This function implements an over-ride of the underline command.
|
1954 |
-
// argument:
|
1955 |
-
// Not used, operates by selection.
|
1956 |
-
// tags:
|
1957 |
-
// protected
|
1958 |
-
if(dojo.isIE){
|
1959 |
-
this._adaptIESelection()
|
1960 |
-
}
|
1961 |
-
return this.document.execCommand("underline", false, argument);
|
1962 |
-
},
|
1963 |
-
|
1964 |
-
_strikethroughImpl: function(argument){
|
1965 |
-
// summary:
|
1966 |
-
// This function implements an over-ride of the strikethrough command.
|
1967 |
-
// argument:
|
1968 |
-
// Not used, operates by selection.
|
1969 |
-
// tags:
|
1970 |
-
// protected
|
1971 |
-
if(dojo.isIE){
|
1972 |
-
this._adaptIESelection()
|
1973 |
-
}
|
1974 |
-
return this.document.execCommand("strikethrough", false, argument);
|
1975 |
-
},
|
1976 |
-
|
1977 |
-
getHeaderHeight: function(){
|
1978 |
-
// summary:
|
1979 |
-
// A function for obtaining the height of the header node
|
1980 |
-
return this._getNodeChildrenHeight(this.header); // Number
|
1981 |
-
},
|
1982 |
-
|
1983 |
-
getFooterHeight: function(){
|
1984 |
-
// summary:
|
1985 |
-
// A function for obtaining the height of the footer node
|
1986 |
-
return this._getNodeChildrenHeight(this.footer); // Number
|
1987 |
-
},
|
1988 |
-
|
1989 |
-
_getNodeChildrenHeight: function(node){
|
1990 |
-
// summary:
|
1991 |
-
// An internal function for computing the cumulative height of all child nodes of 'node'
|
1992 |
-
// node:
|
1993 |
-
// The node to process the children of;
|
1994 |
-
var h = 0;
|
1995 |
-
if(node && node.childNodes){
|
1996 |
-
// IE didn't compute it right when position was obtained on the node directly is some cases,
|
1997 |
-
// so we have to walk over all the children manually.
|
1998 |
-
var i;
|
1999 |
-
for(i = 0; i < node.childNodes.length; i++){
|
2000 |
-
var size = dojo.position(node.childNodes[i]);
|
2001 |
-
h += size.h;
|
2002 |
-
}
|
2003 |
-
}
|
2004 |
-
return h; // Number
|
2005 |
-
},
|
2006 |
-
|
2007 |
-
_isNodeEmpty: function(node, startOffset){
|
2008 |
-
// summary:
|
2009 |
-
// Function to test if a node is devoid of real content.
|
2010 |
-
// node:
|
2011 |
-
// The node to check.
|
2012 |
-
// tags:
|
2013 |
-
// private.
|
2014 |
-
if(node.nodeType == 1/*element*/){
|
2015 |
-
if(node.childNodes.length > 0){
|
2016 |
-
return this._isNodeEmpty(node.childNodes[0], startOffset);
|
2017 |
-
}
|
2018 |
-
return true;
|
2019 |
-
}else if(node.nodeType == 3/*text*/){
|
2020 |
-
return (node.nodeValue.substring(startOffset) == "");
|
2021 |
-
}
|
2022 |
-
return false;
|
2023 |
-
},
|
2024 |
-
|
2025 |
-
_removeStartingRangeFromRange: function(node, range){
|
2026 |
-
// summary:
|
2027 |
-
// Function to adjust selection range by removing the current
|
2028 |
-
// start node.
|
2029 |
-
// node:
|
2030 |
-
// The node to remove from the starting range.
|
2031 |
-
// range:
|
2032 |
-
// The range to adapt.
|
2033 |
-
// tags:
|
2034 |
-
// private
|
2035 |
-
if(node.nextSibling){
|
2036 |
-
range.setStart(node.nextSibling,0);
|
2037 |
-
}else{
|
2038 |
-
var parent = node.parentNode;
|
2039 |
-
while(parent && parent.nextSibling == null){
|
2040 |
-
//move up the tree until we find a parent that has another node, that node will be the next node
|
2041 |
-
parent = parent.parentNode;
|
2042 |
-
}
|
2043 |
-
if(parent){
|
2044 |
-
range.setStart(parent.nextSibling,0);
|
2045 |
-
}
|
2046 |
-
}
|
2047 |
-
return range;
|
2048 |
-
},
|
2049 |
-
|
2050 |
-
_adaptIESelection: function(){
|
2051 |
-
// summary:
|
2052 |
-
// Function to adapt the IE range by removing leading 'newlines'
|
2053 |
-
// Needed to fix issue with bold/italics/underline not working if
|
2054 |
-
// range included leading 'newlines'.
|
2055 |
-
// In IE, if a user starts a selection at the very end of a line,
|
2056 |
-
// then the native browser commands will fail to execute correctly.
|
2057 |
-
// To work around the issue, we can remove all empty nodes from
|
2058 |
-
// the start of the range selection.
|
2059 |
-
var selection = dijit.range.getSelection(this.window);
|
2060 |
-
if(selection && selection.rangeCount && !selection.isCollapsed){
|
2061 |
-
var range = selection.getRangeAt(0);
|
2062 |
-
var firstNode = range.startContainer;
|
2063 |
-
var startOffset = range.startOffset;
|
2064 |
-
|
2065 |
-
while(firstNode.nodeType == 3/*text*/ && startOffset >= firstNode.length && firstNode.nextSibling){
|
2066 |
-
//traverse the text nodes until we get to the one that is actually highlighted
|
2067 |
-
startOffset = startOffset - firstNode.length;
|
2068 |
-
firstNode = firstNode.nextSibling;
|
2069 |
-
}
|
2070 |
-
|
2071 |
-
//Remove the starting ranges until the range does not start with an empty node.
|
2072 |
-
var lastNode=null;
|
2073 |
-
while(this._isNodeEmpty(firstNode, startOffset) && firstNode != lastNode){
|
2074 |
-
lastNode =firstNode; //this will break the loop in case we can't find the next sibling
|
2075 |
-
range = this._removeStartingRangeFromRange(firstNode, range); //move the start container to the next node in the range
|
2076 |
-
firstNode = range.startContainer;
|
2077 |
-
startOffset = 0; //start at the beginning of the new starting range
|
2078 |
-
}
|
2079 |
-
selection.removeAllRanges();// this will work as long as users cannot select multiple ranges. I have not been able to do that in the editor.
|
2080 |
-
selection.addRange(range);
|
2081 |
-
}
|
2082 |
-
}
|
2083 |
-
});
|
2084 |
-
|
2085 |
-
return dijit._editor.RichText;
|
2086 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/127.js
DELETED
@@ -1,1218 +0,0 @@
|
|
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) {
|
2 |
-
|
3 |
-
dojo.declare(
|
4 |
-
"dijit.form.ComboBoxMixin",
|
5 |
-
dijit._HasDropDown,
|
6 |
-
{
|
7 |
-
// summary:
|
8 |
-
// Implements the base functionality for `dijit.form.ComboBox`/`dijit.form.FilteringSelect`
|
9 |
-
// description:
|
10 |
-
// All widgets that mix in dijit.form.ComboBoxMixin must extend `dijit.form._FormValueWidget`.
|
11 |
-
// tags:
|
12 |
-
// protected
|
13 |
-
|
14 |
-
// item: Object
|
15 |
-
// This is the item returned by the dojo.data.store implementation that
|
16 |
-
// provides the data for this ComboBox, it's the currently selected item.
|
17 |
-
item: null,
|
18 |
-
|
19 |
-
// pageSize: Integer
|
20 |
-
// Argument to data provider.
|
21 |
-
// Specifies number of search results per page (before hitting "next" button)
|
22 |
-
pageSize: Infinity,
|
23 |
-
|
24 |
-
// store: [const] Object
|
25 |
-
// Reference to data provider object used by this ComboBox
|
26 |
-
store: null,
|
27 |
-
|
28 |
-
// fetchProperties: Object
|
29 |
-
// Mixin to the dojo.data store's fetch.
|
30 |
-
// For example, to set the sort order of the ComboBox menu, pass:
|
31 |
-
// | { sort: [{attribute:"name",descending: true}] }
|
32 |
-
// To override the default queryOptions so that deep=false, do:
|
33 |
-
// | { queryOptions: {ignoreCase: true, deep: false} }
|
34 |
-
fetchProperties:{},
|
35 |
-
|
36 |
-
// query: Object
|
37 |
-
// A query that can be passed to 'store' to initially filter the items,
|
38 |
-
// before doing further filtering based on `searchAttr` and the key.
|
39 |
-
// Any reference to the `searchAttr` is ignored.
|
40 |
-
query: {},
|
41 |
-
|
42 |
-
// autoComplete: Boolean
|
43 |
-
// If user types in a partial string, and then tab out of the `<input>` box,
|
44 |
-
// automatically copy the first entry displayed in the drop down list to
|
45 |
-
// the `<input>` field
|
46 |
-
autoComplete: true,
|
47 |
-
|
48 |
-
// highlightMatch: String
|
49 |
-
// One of: "first", "all" or "none".
|
50 |
-
//
|
51 |
-
// If the ComboBox/FilteringSelect opens with the search results and the searched
|
52 |
-
// string can be found, it will be highlighted. If set to "all"
|
53 |
-
// then will probably want to change `queryExpr` parameter to '*${0}*'
|
54 |
-
//
|
55 |
-
// Highlighting is only performed when `labelType` is "text", so as to not
|
56 |
-
// interfere with any HTML markup an HTML label might contain.
|
57 |
-
highlightMatch: "first",
|
58 |
-
|
59 |
-
// searchDelay: Integer
|
60 |
-
// Delay in milliseconds between when user types something and we start
|
61 |
-
// searching based on that value
|
62 |
-
searchDelay: 100,
|
63 |
-
|
64 |
-
// searchAttr: String
|
65 |
-
// Search for items in the data store where this attribute (in the item)
|
66 |
-
// matches what the user typed
|
67 |
-
searchAttr: "name",
|
68 |
-
|
69 |
-
// labelAttr: String?
|
70 |
-
// The entries in the drop down list come from this attribute in the
|
71 |
-
// dojo.data items.
|
72 |
-
// If not specified, the searchAttr attribute is used instead.
|
73 |
-
labelAttr: "",
|
74 |
-
|
75 |
-
// labelType: String
|
76 |
-
// Specifies how to interpret the labelAttr in the data store items.
|
77 |
-
// Can be "html" or "text".
|
78 |
-
labelType: "text",
|
79 |
-
|
80 |
-
// queryExpr: String
|
81 |
-
// This specifies what query ComboBox/FilteringSelect sends to the data store,
|
82 |
-
// based on what the user has typed. Changing this expression will modify
|
83 |
-
// whether the drop down shows only exact matches, a "starting with" match,
|
84 |
-
// etc. Use it in conjunction with highlightMatch.
|
85 |
-
// dojo.data query expression pattern.
|
86 |
-
// `${0}` will be substituted for the user text.
|
87 |
-
// `*` is used for wildcards.
|
88 |
-
// `${0}*` means "starts with", `*${0}*` means "contains", `${0}` means "is"
|
89 |
-
queryExpr: "${0}*",
|
90 |
-
|
91 |
-
// ignoreCase: Boolean
|
92 |
-
// Set true if the ComboBox/FilteringSelect should ignore case when matching possible items
|
93 |
-
ignoreCase: true,
|
94 |
-
|
95 |
-
// hasDownArrow: Boolean
|
96 |
-
// Set this textbox to have a down arrow button, to display the drop down list.
|
97 |
-
// Defaults to true.
|
98 |
-
hasDownArrow: true,
|
99 |
-
|
100 |
-
templateString: dojo.cache("dijit.form", "templates/DropDownBox.html"),
|
101 |
-
|
102 |
-
baseClass: "dijitTextBox dijitComboBox",
|
103 |
-
|
104 |
-
// dropDownClass: [protected extension] String
|
105 |
-
// Name of the dropdown widget class used to select a date/time.
|
106 |
-
// Subclasses should specify this.
|
107 |
-
dropDownClass: "dijit.form._ComboBoxMenu",
|
108 |
-
|
109 |
-
// Set classes like dijitDownArrowButtonHover depending on
|
110 |
-
// mouse action over button node
|
111 |
-
cssStateNodes: {
|
112 |
-
"_buttonNode": "dijitDownArrowButton"
|
113 |
-
},
|
114 |
-
|
115 |
-
// Flags to _HasDropDown to limit height of drop down to make it fit in viewport
|
116 |
-
maxHeight: -1,
|
117 |
-
|
118 |
-
// For backwards compatibility let onClick events propagate, even clicks on the down arrow button
|
119 |
-
_stopClickEvents: false,
|
120 |
-
|
121 |
-
_getCaretPos: function(/*DomNode*/ element){
|
122 |
-
// khtml 3.5.2 has selection* methods as does webkit nightlies from 2005-06-22
|
123 |
-
var pos = 0;
|
124 |
-
if(typeof(element.selectionStart) == "number"){
|
125 |
-
// FIXME: this is totally borked on Moz < 1.3. Any recourse?
|
126 |
-
pos = element.selectionStart;
|
127 |
-
}else if(dojo.isIE){
|
128 |
-
// in the case of a mouse click in a popup being handled,
|
129 |
-
// then the dojo.doc.selection is not the textarea, but the popup
|
130 |
-
// var r = dojo.doc.selection.createRange();
|
131 |
-
// hack to get IE 6 to play nice. What a POS browser.
|
132 |
-
var tr = dojo.doc.selection.createRange().duplicate();
|
133 |
-
var ntr = element.createTextRange();
|
134 |
-
tr.move("character",0);
|
135 |
-
ntr.move("character",0);
|
136 |
-
try{
|
137 |
-
// If control doesn't have focus, you get an exception.
|
138 |
-
// Seems to happen on reverse-tab, but can also happen on tab (seems to be a race condition - only happens sometimes).
|
139 |
-
// There appears to be no workaround for this - googled for quite a while.
|
140 |
-
ntr.setEndPoint("EndToEnd", tr);
|
141 |
-
pos = String(ntr.text).replace(/\r/g,"").length;
|
142 |
-
}catch(e){
|
143 |
-
// If focus has shifted, 0 is fine for caret pos.
|
144 |
-
}
|
145 |
-
}
|
146 |
-
return pos;
|
147 |
-
},
|
148 |
-
|
149 |
-
_setCaretPos: function(/*DomNode*/ element, /*Number*/ location){
|
150 |
-
location = parseInt(location);
|
151 |
-
dijit.selectInputText(element, location, location);
|
152 |
-
},
|
153 |
-
|
154 |
-
_setDisabledAttr: function(/*Boolean*/ value){
|
155 |
-
// Additional code to set disabled state of ComboBox node.
|
156 |
-
// Overrides _FormValueWidget._setDisabledAttr() or ValidationTextBox._setDisabledAttr().
|
157 |
-
this.inherited(arguments);
|
158 |
-
dijit.setWaiState(this.domNode, "disabled", value);
|
159 |
-
},
|
160 |
-
|
161 |
-
_abortQuery: function(){
|
162 |
-
// stop in-progress query
|
163 |
-
if(this.searchTimer){
|
164 |
-
clearTimeout(this.searchTimer);
|
165 |
-
this.searchTimer = null;
|
166 |
-
}
|
167 |
-
if(this._fetchHandle){
|
168 |
-
if(this._fetchHandle.abort){ this._fetchHandle.abort(); }
|
169 |
-
this._fetchHandle = null;
|
170 |
-
}
|
171 |
-
},
|
172 |
-
|
173 |
-
_onInput: function(/*Event*/ evt){
|
174 |
-
// summary:
|
175 |
-
// Handles paste events
|
176 |
-
if(!this.searchTimer && (evt.type == 'paste'/*IE|WebKit*/ || evt.type == 'input'/*Firefox*/) && this._lastInput != this.textbox.value){
|
177 |
-
this.searchTimer = setTimeout(dojo.hitch(this, function(){
|
178 |
-
this._onKey({charOrCode: 229}); // fake IME key to cause a search
|
179 |
-
}), 100); // long delay that will probably be preempted by keyboard input
|
180 |
-
}
|
181 |
-
this.inherited(arguments);
|
182 |
-
},
|
183 |
-
|
184 |
-
_onKey: function(/*Event*/ evt){
|
185 |
-
// summary:
|
186 |
-
// Handles keyboard events
|
187 |
-
|
188 |
-
var key = evt.charOrCode;
|
189 |
-
|
190 |
-
// except for cutting/pasting case - ctrl + x/v
|
191 |
-
if(evt.altKey || ((evt.ctrlKey || evt.metaKey) && (key != 'x' && key != 'v')) || key == dojo.keys.SHIFT){
|
192 |
-
return; // throw out weird key combinations and spurious events
|
193 |
-
}
|
194 |
-
|
195 |
-
var doSearch = false;
|
196 |
-
var pw = this.dropDown;
|
197 |
-
var dk = dojo.keys;
|
198 |
-
var highlighted = null;
|
199 |
-
this._prev_key_backspace = false;
|
200 |
-
this._abortQuery();
|
201 |
-
|
202 |
-
// _HasDropDown will do some of the work:
|
203 |
-
// 1. when drop down is not yet shown:
|
204 |
-
// - if user presses the down arrow key, call loadDropDown()
|
205 |
-
// 2. when drop down is already displayed:
|
206 |
-
// - on ESC key, call closeDropDown()
|
207 |
-
// - otherwise, call dropDown.handleKey() to process the keystroke
|
208 |
-
this.inherited(arguments);
|
209 |
-
|
210 |
-
if(this._opened){
|
211 |
-
highlighted = pw.getHighlightedOption();
|
212 |
-
}
|
213 |
-
switch(key){
|
214 |
-
case dk.PAGE_DOWN:
|
215 |
-
case dk.DOWN_ARROW:
|
216 |
-
case dk.PAGE_UP:
|
217 |
-
case dk.UP_ARROW:
|
218 |
-
// Keystroke caused ComboBox_menu to move to a different item.
|
219 |
-
// Copy new item to <input> box.
|
220 |
-
if(this._opened){
|
221 |
-
this._announceOption(highlighted);
|
222 |
-
}
|
223 |
-
dojo.stopEvent(evt);
|
224 |
-
break;
|
225 |
-
|
226 |
-
case dk.ENTER:
|
227 |
-
// prevent submitting form if user presses enter. Also
|
228 |
-
// prevent accepting the value if either Next or Previous
|
229 |
-
// are selected
|
230 |
-
if(highlighted){
|
231 |
-
// only stop event on prev/next
|
232 |
-
if(highlighted == pw.nextButton){
|
233 |
-
this._nextSearch(1);
|
234 |
-
dojo.stopEvent(evt);
|
235 |
-
break;
|
236 |
-
}else if(highlighted == pw.previousButton){
|
237 |
-
this._nextSearch(-1);
|
238 |
-
dojo.stopEvent(evt);
|
239 |
-
break;
|
240 |
-
}
|
241 |
-
}else{
|
242 |
-
// Update 'value' (ex: KY) according to currently displayed text
|
243 |
-
this._setBlurValue(); // set value if needed
|
244 |
-
this._setCaretPos(this.focusNode, this.focusNode.value.length); // move cursor to end and cancel highlighting
|
245 |
-
}
|
246 |
-
// default case:
|
247 |
-
// if enter pressed while drop down is open, or for FilteringSelect,
|
248 |
-
// if we are in the middle of a query to convert a directly typed in value to an item,
|
249 |
-
// prevent submit, but allow event to bubble
|
250 |
-
if(this._opened || this._fetchHandle){
|
251 |
-
evt.preventDefault();
|
252 |
-
}
|
253 |
-
// fall through
|
254 |
-
|
255 |
-
case dk.TAB:
|
256 |
-
var newvalue = this.get('displayedValue');
|
257 |
-
// if the user had More Choices selected fall into the
|
258 |
-
// _onBlur handler
|
259 |
-
if(pw && (
|
260 |
-
newvalue == pw._messages["previousMessage"] ||
|
261 |
-
newvalue == pw._messages["nextMessage"])
|
262 |
-
){
|
263 |
-
break;
|
264 |
-
}
|
265 |
-
if(highlighted){
|
266 |
-
this._selectOption();
|
267 |
-
}
|
268 |
-
if(this._opened){
|
269 |
-
this._lastQuery = null; // in case results come back later
|
270 |
-
this.closeDropDown();
|
271 |
-
}
|
272 |
-
break;
|
273 |
-
|
274 |
-
case ' ':
|
275 |
-
if(highlighted){
|
276 |
-
// user is effectively clicking a choice in the drop down menu
|
277 |
-
dojo.stopEvent(evt);
|
278 |
-
this._selectOption();
|
279 |
-
this.closeDropDown();
|
280 |
-
}else{
|
281 |
-
// user typed a space into the input box, treat as normal character
|
282 |
-
doSearch = true;
|
283 |
-
}
|
284 |
-
break;
|
285 |
-
|
286 |
-
case dk.DELETE:
|
287 |
-
case dk.BACKSPACE:
|
288 |
-
this._prev_key_backspace = true;
|
289 |
-
doSearch = true;
|
290 |
-
break;
|
291 |
-
|
292 |
-
default:
|
293 |
-
// Non char keys (F1-F12 etc..) shouldn't open list.
|
294 |
-
// Ascii characters and IME input (Chinese, Japanese etc.) should.
|
295 |
-
//IME input produces keycode == 229.
|
296 |
-
doSearch = typeof key == 'string' || key == 229;
|
297 |
-
}
|
298 |
-
if(doSearch){
|
299 |
-
// need to wait a tad before start search so that the event
|
300 |
-
// bubbles through DOM and we have value visible
|
301 |
-
this.item = undefined; // undefined means item needs to be set
|
302 |
-
this.searchTimer = setTimeout(dojo.hitch(this, "_startSearchFromInput"),1);
|
303 |
-
}
|
304 |
-
},
|
305 |
-
|
306 |
-
_autoCompleteText: function(/*String*/ text){
|
307 |
-
// summary:
|
308 |
-
// Fill in the textbox with the first item from the drop down
|
309 |
-
// list, and highlight the characters that were
|
310 |
-
// auto-completed. For example, if user typed "CA" and the
|
311 |
-
// drop down list appeared, the textbox would be changed to
|
312 |
-
// "California" and "ifornia" would be highlighted.
|
313 |
-
|
314 |
-
var fn = this.focusNode;
|
315 |
-
|
316 |
-
// IE7: clear selection so next highlight works all the time
|
317 |
-
dijit.selectInputText(fn, fn.value.length);
|
318 |
-
// does text autoComplete the value in the textbox?
|
319 |
-
var caseFilter = this.ignoreCase? 'toLowerCase' : 'substr';
|
320 |
-
if(text[caseFilter](0).indexOf(this.focusNode.value[caseFilter](0)) == 0){
|
321 |
-
var cpos = this._getCaretPos(fn);
|
322 |
-
// only try to extend if we added the last character at the end of the input
|
323 |
-
if((cpos+1) > fn.value.length){
|
324 |
-
// only add to input node as we would overwrite Capitalisation of chars
|
325 |
-
// actually, that is ok
|
326 |
-
fn.value = text;//.substr(cpos);
|
327 |
-
// visually highlight the autocompleted characters
|
328 |
-
dijit.selectInputText(fn, cpos);
|
329 |
-
}
|
330 |
-
}else{
|
331 |
-
// text does not autoComplete; replace the whole value and highlight
|
332 |
-
fn.value = text;
|
333 |
-
dijit.selectInputText(fn);
|
334 |
-
}
|
335 |
-
},
|
336 |
-
|
337 |
-
_openResultList: function(/*Object*/ results, /*Object*/ dataObject){
|
338 |
-
// summary:
|
339 |
-
// Callback when a search completes.
|
340 |
-
// description:
|
341 |
-
// 1. generates drop-down list and calls _showResultList() to display it
|
342 |
-
// 2. if this result list is from user pressing "more choices"/"previous choices"
|
343 |
-
// then tell screen reader to announce new option
|
344 |
-
this._fetchHandle = null;
|
345 |
-
if( this.disabled ||
|
346 |
-
this.readOnly ||
|
347 |
-
(dataObject.query[this.searchAttr] != this._lastQuery)
|
348 |
-
){
|
349 |
-
return;
|
350 |
-
}
|
351 |
-
var wasSelected = this.dropDown._highlighted_option && dojo.hasClass(this.dropDown._highlighted_option, "dijitMenuItemSelected");
|
352 |
-
this.dropDown.clearResultList();
|
353 |
-
if(!results.length && !this._maxOptions){ // if no results and not just the previous choices button
|
354 |
-
this.closeDropDown();
|
355 |
-
return;
|
356 |
-
}
|
357 |
-
|
358 |
-
// Fill in the textbox with the first item from the drop down list,
|
359 |
-
// and highlight the characters that were auto-completed. For
|
360 |
-
// example, if user typed "CA" and the drop down list appeared, the
|
361 |
-
// textbox would be changed to "California" and "ifornia" would be
|
362 |
-
// highlighted.
|
363 |
-
|
364 |
-
dataObject._maxOptions = this._maxOptions;
|
365 |
-
var nodes = this.dropDown.createOptions(
|
366 |
-
results,
|
367 |
-
dataObject,
|
368 |
-
dojo.hitch(this, "_getMenuLabelFromItem")
|
369 |
-
);
|
370 |
-
|
371 |
-
// show our list (only if we have content, else nothing)
|
372 |
-
this._showResultList();
|
373 |
-
|
374 |
-
// #4091:
|
375 |
-
// tell the screen reader that the paging callback finished by
|
376 |
-
// shouting the next choice
|
377 |
-
if(dataObject.direction){
|
378 |
-
if(1 == dataObject.direction){
|
379 |
-
this.dropDown.highlightFirstOption();
|
380 |
-
}else if(-1 == dataObject.direction){
|
381 |
-
this.dropDown.highlightLastOption();
|
382 |
-
}
|
383 |
-
if(wasSelected){
|
384 |
-
this._announceOption(this.dropDown.getHighlightedOption());
|
385 |
-
}
|
386 |
-
}else if(this.autoComplete && !this._prev_key_backspace
|
387 |
-
// when the user clicks the arrow button to show the full list,
|
388 |
-
// startSearch looks for "*".
|
389 |
-
// it does not make sense to autocomplete
|
390 |
-
// if they are just previewing the options available.
|
391 |
-
&& !/^[*]+$/.test(dataObject.query[this.searchAttr])){
|
392 |
-
this._announceOption(nodes[1]); // 1st real item
|
393 |
-
}
|
394 |
-
},
|
395 |
-
|
396 |
-
_showResultList: function(){
|
397 |
-
// summary:
|
398 |
-
// Display the drop down if not already displayed, or if it is displayed, then
|
399 |
-
// reposition it if necessary (reposition may be necessary if drop down's height changed).
|
400 |
-
|
401 |
-
this.closeDropDown(true);
|
402 |
-
|
403 |
-
// hide the tooltip
|
404 |
-
this.displayMessage("");
|
405 |
-
|
406 |
-
this.openDropDown();
|
407 |
-
|
408 |
-
dijit.setWaiState(this.domNode, "expanded", "true");
|
409 |
-
},
|
410 |
-
|
411 |
-
loadDropDown: function(/*Function*/ callback){
|
412 |
-
// Overrides _HasDropDown.loadDropDown().
|
413 |
-
// This is called when user has pressed button icon or pressed the down arrow key
|
414 |
-
// to open the drop down.
|
415 |
-
|
416 |
-
this._startSearchAll();
|
417 |
-
},
|
418 |
-
|
419 |
-
isLoaded: function(){
|
420 |
-
// signal to _HasDropDown that it needs to call loadDropDown() to load the
|
421 |
-
// drop down asynchronously before displaying it
|
422 |
-
return false;
|
423 |
-
},
|
424 |
-
|
425 |
-
closeDropDown: function(){
|
426 |
-
// Overrides _HasDropDown.closeDropDown(). Closes the drop down (assuming that it's open).
|
427 |
-
// This method is the callback when the user types ESC or clicking
|
428 |
-
// the button icon while the drop down is open. It's also called by other code.
|
429 |
-
this._abortQuery();
|
430 |
-
if(this._opened){
|
431 |
-
this.inherited(arguments);
|
432 |
-
dijit.setWaiState(this.domNode, "expanded", "false");
|
433 |
-
dijit.removeWaiState(this.focusNode,"activedescendant");
|
434 |
-
}
|
435 |
-
},
|
436 |
-
|
437 |
-
_setBlurValue: function(){
|
438 |
-
// if the user clicks away from the textbox OR tabs away, set the
|
439 |
-
// value to the textbox value
|
440 |
-
// #4617:
|
441 |
-
// if value is now more choices or previous choices, revert
|
442 |
-
// the value
|
443 |
-
var newvalue = this.get('displayedValue');
|
444 |
-
var pw = this.dropDown;
|
445 |
-
if(pw && (
|
446 |
-
newvalue == pw._messages["previousMessage"] ||
|
447 |
-
newvalue == pw._messages["nextMessage"]
|
448 |
-
)
|
449 |
-
){
|
450 |
-
this._setValueAttr(this._lastValueReported, true);
|
451 |
-
}else if(typeof this.item == "undefined"){
|
452 |
-
// Update 'value' (ex: KY) according to currently displayed text
|
453 |
-
this.item = null;
|
454 |
-
this.set('displayedValue', newvalue);
|
455 |
-
}else{
|
456 |
-
if(this.value != this._lastValueReported){
|
457 |
-
dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true);
|
458 |
-
}
|
459 |
-
this._refreshState();
|
460 |
-
}
|
461 |
-
},
|
462 |
-
|
463 |
-
_onBlur: function(){
|
464 |
-
// summary:
|
465 |
-
// Called magically when focus has shifted away from this widget and it's drop down
|
466 |
-
this.closeDropDown();
|
467 |
-
this.inherited(arguments);
|
468 |
-
},
|
469 |
-
|
470 |
-
_setItemAttr: function(/*item*/ item, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){
|
471 |
-
// summary:
|
472 |
-
// Set the displayed valued in the input box, and the hidden value
|
473 |
-
// that gets submitted, based on a dojo.data store item.
|
474 |
-
// description:
|
475 |
-
// Users shouldn't call this function; they should be calling
|
476 |
-
// set('item', value)
|
477 |
-
// tags:
|
478 |
-
// private
|
479 |
-
if(!displayedValue){
|
480 |
-
displayedValue = this.store.getValue(item, this.searchAttr);
|
481 |
-
}
|
482 |
-
var value = this._getValueField() != this.searchAttr? this.store.getIdentity(item) : displayedValue;
|
483 |
-
this._set("item", item);
|
484 |
-
dijit.form.ComboBox.superclass._setValueAttr.call(this, value, priorityChange, displayedValue);
|
485 |
-
},
|
486 |
-
|
487 |
-
_announceOption: function(/*Node*/ node){
|
488 |
-
// summary:
|
489 |
-
// a11y code that puts the highlighted option in the textbox.
|
490 |
-
// This way screen readers will know what is happening in the
|
491 |
-
// menu.
|
492 |
-
|
493 |
-
if(!node){
|
494 |
-
return;
|
495 |
-
}
|
496 |
-
// pull the text value from the item attached to the DOM node
|
497 |
-
var newValue;
|
498 |
-
if(node == this.dropDown.nextButton ||
|
499 |
-
node == this.dropDown.previousButton){
|
500 |
-
newValue = node.innerHTML;
|
501 |
-
this.item = undefined;
|
502 |
-
this.value = '';
|
503 |
-
}else{
|
504 |
-
newValue = this.store.getValue(node.item, this.searchAttr).toString();
|
505 |
-
this.set('item', node.item, false, newValue);
|
506 |
-
}
|
507 |
-
// get the text that the user manually entered (cut off autocompleted text)
|
508 |
-
this.focusNode.value = this.focusNode.value.substring(0, this._lastInput.length);
|
509 |
-
// set up ARIA activedescendant
|
510 |
-
dijit.setWaiState(this.focusNode, "activedescendant", dojo.attr(node, "id"));
|
511 |
-
// autocomplete the rest of the option to announce change
|
512 |
-
this._autoCompleteText(newValue);
|
513 |
-
},
|
514 |
-
|
515 |
-
_selectOption: function(/*Event*/ evt){
|
516 |
-
// summary:
|
517 |
-
// Menu callback function, called when an item in the menu is selected.
|
518 |
-
if(evt){
|
519 |
-
this._announceOption(evt.target);
|
520 |
-
}
|
521 |
-
this.closeDropDown();
|
522 |
-
this._setCaretPos(this.focusNode, this.focusNode.value.length);
|
523 |
-
dijit.form._FormValueWidget.prototype._setValueAttr.call(this, this.value, true); // set this.value and fire onChange
|
524 |
-
},
|
525 |
-
|
526 |
-
_startSearchAll: function(){
|
527 |
-
this._startSearch('');
|
528 |
-
},
|
529 |
-
|
530 |
-
_startSearchFromInput: function(){
|
531 |
-
this._startSearch(this.focusNode.value.replace(/([\\\*\?])/g, "\\$1"));
|
532 |
-
},
|
533 |
-
|
534 |
-
_getQueryString: function(/*String*/ text){
|
535 |
-
return dojo.string.substitute(this.queryExpr, [text]);
|
536 |
-
},
|
537 |
-
|
538 |
-
_startSearch: function(/*String*/ key){
|
539 |
-
// summary:
|
540 |
-
// Starts a search for elements matching key (key=="" means to return all items),
|
541 |
-
// and calls _openResultList() when the search completes, to display the results.
|
542 |
-
if(!this.dropDown){
|
543 |
-
var popupId = this.id + "_popup",
|
544 |
-
dropDownConstructor = dojo.getObject(this.dropDownClass, false);
|
545 |
-
this.dropDown = new dropDownConstructor({
|
546 |
-
onChange: dojo.hitch(this, this._selectOption),
|
547 |
-
id: popupId,
|
548 |
-
dir: this.dir
|
549 |
-
});
|
550 |
-
dijit.removeWaiState(this.focusNode,"activedescendant");
|
551 |
-
dijit.setWaiState(this.textbox,"owns",popupId); // associate popup with textbox
|
552 |
-
}
|
553 |
-
// create a new query to prevent accidentally querying for a hidden
|
554 |
-
// value from FilteringSelect's keyField
|
555 |
-
var query = dojo.clone(this.query); // #5970
|
556 |
-
this._lastInput = key; // Store exactly what was entered by the user.
|
557 |
-
this._lastQuery = query[this.searchAttr] = this._getQueryString(key);
|
558 |
-
// #5970: set _lastQuery, *then* start the timeout
|
559 |
-
// otherwise, if the user types and the last query returns before the timeout,
|
560 |
-
// _lastQuery won't be set and their input gets rewritten
|
561 |
-
this.searchTimer=setTimeout(dojo.hitch(this, function(query, _this){
|
562 |
-
this.searchTimer = null;
|
563 |
-
var fetch = {
|
564 |
-
queryOptions: {
|
565 |
-
ignoreCase: this.ignoreCase,
|
566 |
-
deep: true
|
567 |
-
},
|
568 |
-
query: query,
|
569 |
-
onBegin: dojo.hitch(this, "_setMaxOptions"),
|
570 |
-
onComplete: dojo.hitch(this, "_openResultList"),
|
571 |
-
onError: function(errText){
|
572 |
-
_this._fetchHandle = null;
|
573 |
-
console.error('dijit.form.ComboBox: ' + errText);
|
574 |
-
_this.closeDropDown();
|
575 |
-
},
|
576 |
-
start: 0,
|
577 |
-
count: this.pageSize
|
578 |
-
};
|
579 |
-
dojo.mixin(fetch, _this.fetchProperties);
|
580 |
-
this._fetchHandle = _this.store.fetch(fetch);
|
581 |
-
|
582 |
-
var nextSearch = function(dataObject, direction){
|
583 |
-
dataObject.start += dataObject.count*direction;
|
584 |
-
// #4091:
|
585 |
-
// tell callback the direction of the paging so the screen
|
586 |
-
// reader knows which menu option to shout
|
587 |
-
dataObject.direction = direction;
|
588 |
-
this._fetchHandle = this.store.fetch(dataObject);
|
589 |
-
this.focus();
|
590 |
-
};
|
591 |
-
this._nextSearch = this.dropDown.onPage = dojo.hitch(this, nextSearch, this._fetchHandle);
|
592 |
-
}, query, this), this.searchDelay);
|
593 |
-
},
|
594 |
-
|
595 |
-
_setMaxOptions: function(size, request){
|
596 |
-
this._maxOptions = size;
|
597 |
-
},
|
598 |
-
|
599 |
-
_getValueField: function(){
|
600 |
-
// summary:
|
601 |
-
// Helper for postMixInProperties() to set this.value based on data inlined into the markup.
|
602 |
-
// Returns the attribute name in the item (in dijit.form._ComboBoxDataStore) to use as the value.
|
603 |
-
return this.searchAttr;
|
604 |
-
},
|
605 |
-
|
606 |
-
//////////// INITIALIZATION METHODS ///////////////////////////////////////
|
607 |
-
|
608 |
-
constructor: function(){
|
609 |
-
this.query={};
|
610 |
-
this.fetchProperties={};
|
611 |
-
},
|
612 |
-
|
613 |
-
postMixInProperties: function(){
|
614 |
-
if(!this.store){
|
615 |
-
var srcNodeRef = this.srcNodeRef;
|
616 |
-
|
617 |
-
// if user didn't specify store, then assume there are option tags
|
618 |
-
this.store = new dijit.form._ComboBoxDataStore(srcNodeRef);
|
619 |
-
|
620 |
-
// if there is no value set and there is an option list, set
|
621 |
-
// the value to the first value to be consistent with native
|
622 |
-
// Select
|
623 |
-
|
624 |
-
// Firefox and Safari set value
|
625 |
-
// IE6 and Opera set selectedIndex, which is automatically set
|
626 |
-
// by the selected attribute of an option tag
|
627 |
-
// IE6 does not set value, Opera sets value = selectedIndex
|
628 |
-
if(!("value" in this.params)){
|
629 |
-
var item = (this.item = this.store.fetchSelectedItem());
|
630 |
-
if(item){
|
631 |
-
var valueField = this._getValueField();
|
632 |
-
this.value = this.store.getValue(item, valueField);
|
633 |
-
}
|
634 |
-
}
|
635 |
-
}
|
636 |
-
|
637 |
-
this.inherited(arguments);
|
638 |
-
},
|
639 |
-
|
640 |
-
postCreate: function(){
|
641 |
-
// summary:
|
642 |
-
// Subclasses must call this method from their postCreate() methods
|
643 |
-
// tags:
|
644 |
-
// protected
|
645 |
-
|
646 |
-
// find any associated label element and add to ComboBox node.
|
647 |
-
var label=dojo.query('label[for="'+this.id+'"]');
|
648 |
-
if(label.length){
|
649 |
-
label[0].id = (this.id+"_label");
|
650 |
-
dijit.setWaiState(this.domNode, "labelledby", label[0].id);
|
651 |
-
|
652 |
-
}
|
653 |
-
this.inherited(arguments);
|
654 |
-
},
|
655 |
-
|
656 |
-
_setHasDownArrowAttr: function(val){
|
657 |
-
this.hasDownArrow = val;
|
658 |
-
this._buttonNode.style.display = val ? "" : "none";
|
659 |
-
},
|
660 |
-
|
661 |
-
_getMenuLabelFromItem: function(/*Item*/ item){
|
662 |
-
var label = this.labelFunc(item, this.store),
|
663 |
-
labelType = this.labelType;
|
664 |
-
// If labelType is not "text" we don't want to screw any markup ot whatever.
|
665 |
-
if(this.highlightMatch != "none" && this.labelType == "text" && this._lastInput){
|
666 |
-
label = this.doHighlight(label, this._escapeHtml(this._lastInput));
|
667 |
-
labelType = "html";
|
668 |
-
}
|
669 |
-
return {html: labelType == "html", label: label};
|
670 |
-
},
|
671 |
-
|
672 |
-
doHighlight: function(/*String*/ label, /*String*/ find){
|
673 |
-
// summary:
|
674 |
-
// Highlights the string entered by the user in the menu. By default this
|
675 |
-
// highlights the first occurrence found. Override this method
|
676 |
-
// to implement your custom highlighting.
|
677 |
-
// tags:
|
678 |
-
// protected
|
679 |
-
|
680 |
-
var
|
681 |
-
// Add (g)lobal modifier when this.highlightMatch == "all" and (i)gnorecase when this.ignoreCase == true
|
682 |
-
modifiers = (this.ignoreCase ? "i" : "") + (this.highlightMatch == "all" ? "g" : ""),
|
683 |
-
i = this.queryExpr.indexOf("${0}");
|
684 |
-
find = dojo.regexp.escapeString(find); // escape regexp special chars
|
685 |
-
return this._escapeHtml(label).replace(
|
686 |
-
// prepend ^ when this.queryExpr == "${0}*" and append $ when this.queryExpr == "*${0}"
|
687 |
-
new RegExp((i == 0 ? "^" : "") + "("+ find +")" + (i == (this.queryExpr.length - 4) ? "$" : ""), modifiers),
|
688 |
-
'<span class="dijitComboBoxHighlightMatch">$1</span>'
|
689 |
-
); // returns String, (almost) valid HTML (entities encoded)
|
690 |
-
},
|
691 |
-
|
692 |
-
_escapeHtml: function(/*String*/ str){
|
693 |
-
// TODO Should become dojo.html.entities(), when exists use instead
|
694 |
-
// summary:
|
695 |
-
// Adds escape sequences for special characters in XML: &<>"'
|
696 |
-
str = String(str).replace(/&/gm, "&").replace(/</gm, "<")
|
697 |
-
.replace(/>/gm, ">").replace(/"/gm, """);
|
698 |
-
return str; // string
|
699 |
-
},
|
700 |
-
|
701 |
-
reset: function(){
|
702 |
-
// Overrides the _FormWidget.reset().
|
703 |
-
// Additionally reset the .item (to clean up).
|
704 |
-
this.item = null;
|
705 |
-
this.inherited(arguments);
|
706 |
-
},
|
707 |
-
|
708 |
-
labelFunc: function(/*item*/ item, /*dojo.data.store*/ store){
|
709 |
-
// summary:
|
710 |
-
// Computes the label to display based on the dojo.data store item.
|
711 |
-
// returns:
|
712 |
-
// The label that the ComboBox should display
|
713 |
-
// tags:
|
714 |
-
// private
|
715 |
-
|
716 |
-
// Use toString() because XMLStore returns an XMLItem whereas this
|
717 |
-
// method is expected to return a String (#9354)
|
718 |
-
return store.getValue(item, this.labelAttr || this.searchAttr).toString(); // String
|
719 |
-
}
|
720 |
-
}
|
721 |
-
);
|
722 |
-
|
723 |
-
dojo.declare(
|
724 |
-
"dijit.form._ComboBoxMenu",
|
725 |
-
[dijit._Widget, dijit._Templated, dijit._CssStateMixin],
|
726 |
-
{
|
727 |
-
// summary:
|
728 |
-
// Focus-less menu for internal use in `dijit.form.ComboBox`
|
729 |
-
// tags:
|
730 |
-
// private
|
731 |
-
|
732 |
-
templateString: "<ul class='dijitReset dijitMenu' dojoAttachEvent='onmousedown:_onMouseDown,onmouseup:_onMouseUp,onmouseover:_onMouseOver,onmouseout:_onMouseOut' style='overflow: \"auto\"; overflow-x: \"hidden\";'>"
|
733 |
-
+"<li class='dijitMenuItem dijitMenuPreviousButton' dojoAttachPoint='previousButton' role='option'></li>"
|
734 |
-
+"<li class='dijitMenuItem dijitMenuNextButton' dojoAttachPoint='nextButton' role='option'></li>"
|
735 |
-
+"</ul>",
|
736 |
-
|
737 |
-
// _messages: Object
|
738 |
-
// Holds "next" and "previous" text for paging buttons on drop down
|
739 |
-
_messages: null,
|
740 |
-
|
741 |
-
baseClass: "dijitComboBoxMenu",
|
742 |
-
|
743 |
-
postMixInProperties: function(){
|
744 |
-
this.inherited(arguments);
|
745 |
-
this._messages = dojo.i18n.getLocalization("dijit.form", "ComboBox", this.lang);
|
746 |
-
},
|
747 |
-
|
748 |
-
buildRendering: function(){
|
749 |
-
this.inherited(arguments);
|
750 |
-
|
751 |
-
// fill in template with i18n messages
|
752 |
-
this.previousButton.innerHTML = this._messages["previousMessage"];
|
753 |
-
this.nextButton.innerHTML = this._messages["nextMessage"];
|
754 |
-
},
|
755 |
-
|
756 |
-
_setValueAttr: function(/*Object*/ value){
|
757 |
-
this.value = value;
|
758 |
-
this.onChange(value);
|
759 |
-
},
|
760 |
-
|
761 |
-
// stubs
|
762 |
-
onChange: function(/*Object*/ value){
|
763 |
-
// summary:
|
764 |
-
// Notifies ComboBox/FilteringSelect that user clicked an option in the drop down menu.
|
765 |
-
// Probably should be called onSelect.
|
766 |
-
// tags:
|
767 |
-
// callback
|
768 |
-
},
|
769 |
-
onPage: function(/*Number*/ direction){
|
770 |
-
// summary:
|
771 |
-
// Notifies ComboBox/FilteringSelect that user clicked to advance to next/previous page.
|
772 |
-
// tags:
|
773 |
-
// callback
|
774 |
-
},
|
775 |
-
|
776 |
-
onClose: function(){
|
777 |
-
// summary:
|
778 |
-
// Callback from dijit.popup code to this widget, notifying it that it closed
|
779 |
-
// tags:
|
780 |
-
// private
|
781 |
-
this._blurOptionNode();
|
782 |
-
},
|
783 |
-
|
784 |
-
_createOption: function(/*Object*/ item, labelFunc){
|
785 |
-
// summary:
|
786 |
-
// Creates an option to appear on the popup menu subclassed by
|
787 |
-
// `dijit.form.FilteringSelect`.
|
788 |
-
|
789 |
-
var menuitem = dojo.create("li", {
|
790 |
-
"class": "dijitReset dijitMenuItem" +(this.isLeftToRight() ? "" : " dijitMenuItemRtl"),
|
791 |
-
role: "option"
|
792 |
-
});
|
793 |
-
var labelObject = labelFunc(item);
|
794 |
-
if(labelObject.html){
|
795 |
-
menuitem.innerHTML = labelObject.label;
|
796 |
-
}else{
|
797 |
-
menuitem.appendChild(
|
798 |
-
dojo.doc.createTextNode(labelObject.label)
|
799 |
-
);
|
800 |
-
}
|
801 |
-
// #3250: in blank options, assign a normal height
|
802 |
-
if(menuitem.innerHTML == ""){
|
803 |
-
menuitem.innerHTML = " ";
|
804 |
-
}
|
805 |
-
menuitem.item=item;
|
806 |
-
return menuitem;
|
807 |
-
},
|
808 |
-
|
809 |
-
createOptions: function(results, dataObject, labelFunc){
|
810 |
-
// summary:
|
811 |
-
// Fills in the items in the drop down list
|
812 |
-
// results:
|
813 |
-
// Array of dojo.data items
|
814 |
-
// dataObject:
|
815 |
-
// dojo.data store
|
816 |
-
// labelFunc:
|
817 |
-
// Function to produce a label in the drop down list from a dojo.data item
|
818 |
-
|
819 |
-
//this._dataObject=dataObject;
|
820 |
-
//this._dataObject.onComplete=dojo.hitch(comboBox, comboBox._openResultList);
|
821 |
-
// display "Previous . . ." button
|
822 |
-
this.previousButton.style.display = (dataObject.start == 0) ? "none" : "";
|
823 |
-
dojo.attr(this.previousButton, "id", this.id + "_prev");
|
824 |
-
// create options using _createOption function defined by parent
|
825 |
-
// ComboBox (or FilteringSelect) class
|
826 |
-
// #2309:
|
827 |
-
// iterate over cache nondestructively
|
828 |
-
dojo.forEach(results, function(item, i){
|
829 |
-
var menuitem = this._createOption(item, labelFunc);
|
830 |
-
dojo.attr(menuitem, "id", this.id + i);
|
831 |
-
this.domNode.insertBefore(menuitem, this.nextButton);
|
832 |
-
}, this);
|
833 |
-
// display "Next . . ." button
|
834 |
-
var displayMore = false;
|
835 |
-
//Try to determine if we should show 'more'...
|
836 |
-
if(dataObject._maxOptions && dataObject._maxOptions != -1){
|
837 |
-
if((dataObject.start + dataObject.count) < dataObject._maxOptions){
|
838 |
-
displayMore = true;
|
839 |
-
}else if((dataObject.start + dataObject.count) > dataObject._maxOptions && dataObject.count == results.length){
|
840 |
-
//Weird return from a datastore, where a start + count > maxOptions
|
841 |
-
// implies maxOptions isn't really valid and we have to go into faking it.
|
842 |
-
//And more or less assume more if count == results.length
|
843 |
-
displayMore = true;
|
844 |
-
}
|
845 |
-
}else if(dataObject.count == results.length){
|
846 |
-
//Don't know the size, so we do the best we can based off count alone.
|
847 |
-
//So, if we have an exact match to count, assume more.
|
848 |
-
displayMore = true;
|
849 |
-
}
|
850 |
-
|
851 |
-
this.nextButton.style.display = displayMore ? "" : "none";
|
852 |
-
dojo.attr(this.nextButton,"id", this.id + "_next");
|
853 |
-
return this.domNode.childNodes;
|
854 |
-
},
|
855 |
-
|
856 |
-
clearResultList: function(){
|
857 |
-
// summary:
|
858 |
-
// Clears the entries in the drop down list, but of course keeps the previous and next buttons.
|
859 |
-
while(this.domNode.childNodes.length>2){
|
860 |
-
this.domNode.removeChild(this.domNode.childNodes[this.domNode.childNodes.length-2]);
|
861 |
-
}
|
862 |
-
this._blurOptionNode();
|
863 |
-
},
|
864 |
-
|
865 |
-
_onMouseDown: function(/*Event*/ evt){
|
866 |
-
dojo.stopEvent(evt);
|
867 |
-
},
|
868 |
-
|
869 |
-
_onMouseUp: function(/*Event*/ evt){
|
870 |
-
if(evt.target === this.domNode || !this._highlighted_option){
|
871 |
-
// !this._highlighted_option check to prevent immediate selection when menu appears on top
|
872 |
-
// of <input>, see #9898. Note that _HasDropDown also has code to prevent this.
|
873 |
-
return;
|
874 |
-
}else if(evt.target == this.previousButton){
|
875 |
-
this._blurOptionNode();
|
876 |
-
this.onPage(-1);
|
877 |
-
}else if(evt.target == this.nextButton){
|
878 |
-
this._blurOptionNode();
|
879 |
-
this.onPage(1);
|
880 |
-
}else{
|
881 |
-
var tgt = evt.target;
|
882 |
-
// while the clicked node is inside the div
|
883 |
-
while(!tgt.item){
|
884 |
-
// recurse to the top
|
885 |
-
tgt = tgt.parentNode;
|
886 |
-
}
|
887 |
-
this._setValueAttr({ target: tgt }, true);
|
888 |
-
}
|
889 |
-
},
|
890 |
-
|
891 |
-
_onMouseOver: function(/*Event*/ evt){
|
892 |
-
if(evt.target === this.domNode){ return; }
|
893 |
-
var tgt = evt.target;
|
894 |
-
if(!(tgt == this.previousButton || tgt == this.nextButton)){
|
895 |
-
// while the clicked node is inside the div
|
896 |
-
while(!tgt.item){
|
897 |
-
// recurse to the top
|
898 |
-
tgt = tgt.parentNode;
|
899 |
-
}
|
900 |
-
}
|
901 |
-
this._focusOptionNode(tgt);
|
902 |
-
},
|
903 |
-
|
904 |
-
_onMouseOut: function(/*Event*/ evt){
|
905 |
-
if(evt.target === this.domNode){ return; }
|
906 |
-
this._blurOptionNode();
|
907 |
-
},
|
908 |
-
|
909 |
-
_focusOptionNode: function(/*DomNode*/ node){
|
910 |
-
// summary:
|
911 |
-
// Does the actual highlight.
|
912 |
-
if(this._highlighted_option != node){
|
913 |
-
this._blurOptionNode();
|
914 |
-
this._highlighted_option = node;
|
915 |
-
dojo.addClass(this._highlighted_option, "dijitMenuItemSelected");
|
916 |
-
}
|
917 |
-
},
|
918 |
-
|
919 |
-
_blurOptionNode: function(){
|
920 |
-
// summary:
|
921 |
-
// Removes highlight on highlighted option.
|
922 |
-
if(this._highlighted_option){
|
923 |
-
dojo.removeClass(this._highlighted_option, "dijitMenuItemSelected");
|
924 |
-
this._highlighted_option = null;
|
925 |
-
}
|
926 |
-
},
|
927 |
-
|
928 |
-
_highlightNextOption: function(){
|
929 |
-
// summary:
|
930 |
-
// Highlight the item just below the current selection.
|
931 |
-
// If nothing selected, highlight first option.
|
932 |
-
|
933 |
-
// because each press of a button clears the menu,
|
934 |
-
// the highlighted option sometimes becomes detached from the menu!
|
935 |
-
// test to see if the option has a parent to see if this is the case.
|
936 |
-
if(!this.getHighlightedOption()){
|
937 |
-
var fc = this.domNode.firstChild;
|
938 |
-
this._focusOptionNode(fc.style.display == "none" ? fc.nextSibling : fc);
|
939 |
-
}else{
|
940 |
-
var ns = this._highlighted_option.nextSibling;
|
941 |
-
if(ns && ns.style.display != "none"){
|
942 |
-
this._focusOptionNode(ns);
|
943 |
-
}else{
|
944 |
-
this.highlightFirstOption();
|
945 |
-
}
|
946 |
-
}
|
947 |
-
// scrollIntoView is called outside of _focusOptionNode because in IE putting it inside causes the menu to scroll up on mouseover
|
948 |
-
dojo.window.scrollIntoView(this._highlighted_option);
|
949 |
-
},
|
950 |
-
|
951 |
-
highlightFirstOption: function(){
|
952 |
-
// summary:
|
953 |
-
// Highlight the first real item in the list (not Previous Choices).
|
954 |
-
var first = this.domNode.firstChild;
|
955 |
-
var second = first.nextSibling;
|
956 |
-
this._focusOptionNode(second.style.display == "none" ? first : second); // remotely possible that Previous Choices is the only thing in the list
|
957 |
-
dojo.window.scrollIntoView(this._highlighted_option);
|
958 |
-
},
|
959 |
-
|
960 |
-
highlightLastOption: function(){
|
961 |
-
// summary:
|
962 |
-
// Highlight the last real item in the list (not More Choices).
|
963 |
-
this._focusOptionNode(this.domNode.lastChild.previousSibling);
|
964 |
-
dojo.window.scrollIntoView(this._highlighted_option);
|
965 |
-
},
|
966 |
-
|
967 |
-
_highlightPrevOption: function(){
|
968 |
-
// summary:
|
969 |
-
// Highlight the item just above the current selection.
|
970 |
-
// If nothing selected, highlight last option (if
|
971 |
-
// you select Previous and try to keep scrolling up the list).
|
972 |
-
if(!this.getHighlightedOption()){
|
973 |
-
var lc = this.domNode.lastChild;
|
974 |
-
this._focusOptionNode(lc.style.display == "none" ? lc.previousSibling : lc);
|
975 |
-
}else{
|
976 |
-
var ps = this._highlighted_option.previousSibling;
|
977 |
-
if(ps && ps.style.display != "none"){
|
978 |
-
this._focusOptionNode(ps);
|
979 |
-
}else{
|
980 |
-
this.highlightLastOption();
|
981 |
-
}
|
982 |
-
}
|
983 |
-
dojo.window.scrollIntoView(this._highlighted_option);
|
984 |
-
},
|
985 |
-
|
986 |
-
_page: function(/*Boolean*/ up){
|
987 |
-
// summary:
|
988 |
-
// Handles page-up and page-down keypresses
|
989 |
-
|
990 |
-
var scrollamount = 0;
|
991 |
-
var oldscroll = this.domNode.scrollTop;
|
992 |
-
var height = dojo.style(this.domNode, "height");
|
993 |
-
// if no item is highlighted, highlight the first option
|
994 |
-
if(!this.getHighlightedOption()){
|
995 |
-
this._highlightNextOption();
|
996 |
-
}
|
997 |
-
while(scrollamount<height){
|
998 |
-
if(up){
|
999 |
-
// stop at option 1
|
1000 |
-
if(!this.getHighlightedOption().previousSibling ||
|
1001 |
-
this._highlighted_option.previousSibling.style.display == "none"){
|
1002 |
-
break;
|
1003 |
-
}
|
1004 |
-
this._highlightPrevOption();
|
1005 |
-
}else{
|
1006 |
-
// stop at last option
|
1007 |
-
if(!this.getHighlightedOption().nextSibling ||
|
1008 |
-
this._highlighted_option.nextSibling.style.display == "none"){
|
1009 |
-
break;
|
1010 |
-
}
|
1011 |
-
this._highlightNextOption();
|
1012 |
-
}
|
1013 |
-
// going backwards
|
1014 |
-
var newscroll=this.domNode.scrollTop;
|
1015 |
-
scrollamount+=(newscroll-oldscroll)*(up ? -1:1);
|
1016 |
-
oldscroll=newscroll;
|
1017 |
-
}
|
1018 |
-
},
|
1019 |
-
|
1020 |
-
pageUp: function(){
|
1021 |
-
// summary:
|
1022 |
-
// Handles pageup keypress.
|
1023 |
-
// TODO: just call _page directly from handleKey().
|
1024 |
-
// tags:
|
1025 |
-
// private
|
1026 |
-
this._page(true);
|
1027 |
-
},
|
1028 |
-
|
1029 |
-
pageDown: function(){
|
1030 |
-
// summary:
|
1031 |
-
// Handles pagedown keypress.
|
1032 |
-
// TODO: just call _page directly from handleKey().
|
1033 |
-
// tags:
|
1034 |
-
// private
|
1035 |
-
this._page(false);
|
1036 |
-
},
|
1037 |
-
|
1038 |
-
getHighlightedOption: function(){
|
1039 |
-
// summary:
|
1040 |
-
// Returns the highlighted option.
|
1041 |
-
var ho = this._highlighted_option;
|
1042 |
-
return (ho && ho.parentNode) ? ho : null;
|
1043 |
-
},
|
1044 |
-
|
1045 |
-
handleKey: function(evt){
|
1046 |
-
// summary:
|
1047 |
-
// Handle keystroke event forwarded from ComboBox, returning false if it's
|
1048 |
-
// a keystroke I recognize and process, true otherwise.
|
1049 |
-
switch(evt.charOrCode){
|
1050 |
-
case dojo.keys.DOWN_ARROW:
|
1051 |
-
this._highlightNextOption();
|
1052 |
-
return false;
|
1053 |
-
case dojo.keys.PAGE_DOWN:
|
1054 |
-
this.pageDown();
|
1055 |
-
return false;
|
1056 |
-
case dojo.keys.UP_ARROW:
|
1057 |
-
this._highlightPrevOption();
|
1058 |
-
return false;
|
1059 |
-
case dojo.keys.PAGE_UP:
|
1060 |
-
this.pageUp();
|
1061 |
-
return false;
|
1062 |
-
default:
|
1063 |
-
return true;
|
1064 |
-
}
|
1065 |
-
}
|
1066 |
-
}
|
1067 |
-
);
|
1068 |
-
|
1069 |
-
dojo.declare(
|
1070 |
-
"dijit.form.ComboBox",
|
1071 |
-
[dijit.form.ValidationTextBox, dijit.form.ComboBoxMixin],
|
1072 |
-
{
|
1073 |
-
// summary:
|
1074 |
-
// Auto-completing text box, and base class for dijit.form.FilteringSelect.
|
1075 |
-
//
|
1076 |
-
// description:
|
1077 |
-
// The drop down box's values are populated from an class called
|
1078 |
-
// a data provider, which returns a list of values based on the characters
|
1079 |
-
// that the user has typed into the input box.
|
1080 |
-
// If OPTION tags are used as the data provider via markup,
|
1081 |
-
// then the OPTION tag's child text node is used as the widget value
|
1082 |
-
// when selected. The OPTION tag's value attribute is ignored.
|
1083 |
-
// To set the default value when using OPTION tags, specify the selected
|
1084 |
-
// attribute on 1 of the child OPTION tags.
|
1085 |
-
//
|
1086 |
-
// Some of the options to the ComboBox are actually arguments to the data
|
1087 |
-
// provider.
|
1088 |
-
|
1089 |
-
_setValueAttr: function(/*String*/ value, /*Boolean?*/ priorityChange, /*String?*/ displayedValue){
|
1090 |
-
// summary:
|
1091 |
-
// Hook so set('value', value) works.
|
1092 |
-
// description:
|
1093 |
-
// Sets the value of the select.
|
1094 |
-
this._set("item", null); // value not looked up in store
|
1095 |
-
if(!value){ value = ''; } // null translates to blank
|
1096 |
-
dijit.form.ValidationTextBox.prototype._setValueAttr.call(this, value, priorityChange, displayedValue);
|
1097 |
-
}
|
1098 |
-
}
|
1099 |
-
);
|
1100 |
-
|
1101 |
-
dojo.declare("dijit.form._ComboBoxDataStore", null, {
|
1102 |
-
// summary:
|
1103 |
-
// Inefficient but small data store specialized for inlined `dijit.form.ComboBox` data
|
1104 |
-
//
|
1105 |
-
// description:
|
1106 |
-
// Provides a store for inlined data like:
|
1107 |
-
//
|
1108 |
-
// | <select>
|
1109 |
-
// | <option value="AL">Alabama</option>
|
1110 |
-
// | ...
|
1111 |
-
//
|
1112 |
-
// Actually. just implements the subset of dojo.data.Read/Notification
|
1113 |
-
// needed for ComboBox and FilteringSelect to work.
|
1114 |
-
//
|
1115 |
-
// Note that an item is just a pointer to the <option> DomNode.
|
1116 |
-
|
1117 |
-
constructor: function( /*DomNode*/ root){
|
1118 |
-
this.root = root;
|
1119 |
-
if(root.tagName != "SELECT" && root.firstChild){
|
1120 |
-
root = dojo.query("select", root);
|
1121 |
-
if(root.length > 0){ // SELECT is a child of srcNodeRef
|
1122 |
-
root = root[0];
|
1123 |
-
}else{ // no select, so create 1 to parent the option tags to define selectedIndex
|
1124 |
-
|
1125 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
1126 |
-
// this.root.innerHTML = "<SELECT>"+this.root.innerHTML+"</SELECT>";
|
1127 |
-
// FIXED:
|
1128 |
-
|
1129 |
-
root = this.root.firstChild;
|
1130 |
-
}
|
1131 |
-
this.root = root;
|
1132 |
-
}
|
1133 |
-
dojo.query("> option", root).forEach(function(node){
|
1134 |
-
// TODO: this was added in #3858 but unclear why/if it's needed; doesn't seem to be.
|
1135 |
-
// If it is needed then can we just hide the select itself instead?
|
1136 |
-
//node.style.display="none";
|
1137 |
-
node.innerHTML = dojo.trim(node.innerHTML);
|
1138 |
-
});
|
1139 |
-
|
1140 |
-
},
|
1141 |
-
|
1142 |
-
getValue: function( /*item*/ item,
|
1143 |
-
/*attribute-name-string*/ attribute,
|
1144 |
-
/*value?*/ defaultValue){
|
1145 |
-
return (attribute == "value") ? item.value : (item.innerText || item.textContent || '');
|
1146 |
-
},
|
1147 |
-
|
1148 |
-
isItemLoaded: function(/*anything*/ something){
|
1149 |
-
return true;
|
1150 |
-
},
|
1151 |
-
|
1152 |
-
getFeatures: function(){
|
1153 |
-
return {"dojo.data.api.Read": true, "dojo.data.api.Identity": true};
|
1154 |
-
},
|
1155 |
-
|
1156 |
-
_fetchItems: function( /*Object*/ args,
|
1157 |
-
/*Function*/ findCallback,
|
1158 |
-
/*Function*/ errorCallback){
|
1159 |
-
// summary:
|
1160 |
-
// See dojo.data.util.simpleFetch.fetch()
|
1161 |
-
if(!args.query){ args.query = {}; }
|
1162 |
-
if(!args.query.name){ args.query.name = ""; }
|
1163 |
-
if(!args.queryOptions){ args.queryOptions = {}; }
|
1164 |
-
var matcher = dojo.data.util.filter.patternToRegExp(args.query.name, args.queryOptions.ignoreCase),
|
1165 |
-
items = dojo.query("> option", this.root).filter(function(option){
|
1166 |
-
return (option.innerText || option.textContent || '').match(matcher);
|
1167 |
-
} );
|
1168 |
-
if(args.sort){
|
1169 |
-
items.sort(dojo.data.util.sorter.createSortFunction(args.sort, this));
|
1170 |
-
}
|
1171 |
-
findCallback(items, args);
|
1172 |
-
},
|
1173 |
-
|
1174 |
-
close: function(/*dojo.data.api.Request || args || null*/ request){
|
1175 |
-
return;
|
1176 |
-
},
|
1177 |
-
|
1178 |
-
getLabel: function(/*item*/ item){
|
1179 |
-
return item.innerHTML;
|
1180 |
-
},
|
1181 |
-
|
1182 |
-
getIdentity: function(/*item*/ item){
|
1183 |
-
return dojo.attr(item, "value");
|
1184 |
-
},
|
1185 |
-
|
1186 |
-
fetchItemByIdentity: function(/*Object*/ args){
|
1187 |
-
// summary:
|
1188 |
-
// Given the identity of an item, this method returns the item that has
|
1189 |
-
// that identity through the onItem callback.
|
1190 |
-
// Refer to dojo.data.api.Identity.fetchItemByIdentity() for more details.
|
1191 |
-
//
|
1192 |
-
// description:
|
1193 |
-
// Given arguments like:
|
1194 |
-
//
|
1195 |
-
// | {identity: "CA", onItem: function(item){...}
|
1196 |
-
//
|
1197 |
-
// Call `onItem()` with the DOM node `<option value="CA">California</option>`
|
1198 |
-
var item = dojo.query("> option[value='" + args.identity + "']", this.root)[0];
|
1199 |
-
args.onItem(item);
|
1200 |
-
},
|
1201 |
-
|
1202 |
-
fetchSelectedItem: function(){
|
1203 |
-
// summary:
|
1204 |
-
// Get the option marked as selected, like `<option selected>`.
|
1205 |
-
// Not part of dojo.data API.
|
1206 |
-
var root = this.root,
|
1207 |
-
si = root.selectedIndex;
|
1208 |
-
return typeof si == "number"
|
1209 |
-
? dojo.query("> option:nth-child(" + (si != -1 ? si+1 : 1) + ")", root)[0]
|
1210 |
-
: null; // dojo.data.Item
|
1211 |
-
}
|
1212 |
-
});
|
1213 |
-
//Mix in the simple fetch implementation to this class.
|
1214 |
-
dojo.extend(dijit.form._ComboBoxDataStore,dojo.data.util.simpleFetch);
|
1215 |
-
|
1216 |
-
|
1217 |
-
return dijit.form.ComboBox;
|
1218 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/128.js
DELETED
@@ -1,11 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
|
3 |
-
Available via Academic Free License >= 2.1 OR the modified BSD license.
|
4 |
-
see: http://dojotoolkit.org/license for details
|
5 |
-
*/
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
|
10 |
-
// 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);}
|
11 |
-
// FIXED:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/129.js
DELETED
@@ -1,1046 +0,0 @@
|
|
1 |
-
define("dojox/data/AndOrReadStore", ["dojo", "dojox", "dojo/data/util/filter", "dojo/data/util/simpleFetch", "dojo/date/stamp"], function(dojo, dojox) {
|
2 |
-
|
3 |
-
dojo.declare("dojox.data.AndOrReadStore", null,{
|
4 |
-
// summary:
|
5 |
-
// AndOrReadStore uses ItemFileReadStore as a base, modifying only the query (_fetchItems) section.
|
6 |
-
// Supports queries of the form: query:"id:1* OR dept:'Sales Department' || (id:2* && NOT dept:S*)"
|
7 |
-
// Includes legacy/widget support via:
|
8 |
-
// query:{complexQuery:"id:1* OR dept:'Sales Department' || (id:2* && NOT dept:S*)"}
|
9 |
-
// The ItemFileReadStore implements the dojo.data.api.Read API and reads
|
10 |
-
// data from JSON files that have contents in this format --
|
11 |
-
// { items: [
|
12 |
-
// { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
|
13 |
-
// { name:'Fozzie Bear', wears:['hat', 'tie']},
|
14 |
-
// { name:'Miss Piggy', pets:'Foo-Foo'}
|
15 |
-
// ]}
|
16 |
-
// Note that it can also contain an 'identifer' property that specified which attribute on the items
|
17 |
-
// in the array of items that acts as the unique identifier for that item.
|
18 |
-
//
|
19 |
-
constructor: function(/* Object */ keywordParameters){
|
20 |
-
// summary: constructor
|
21 |
-
// keywordParameters: {url: String}
|
22 |
-
// keywordParameters: {data: jsonObject}
|
23 |
-
// keywordParameters: {typeMap: object)
|
24 |
-
// The structure of the typeMap object is as follows:
|
25 |
-
// {
|
26 |
-
// type0: function || object,
|
27 |
-
// type1: function || object,
|
28 |
-
// ...
|
29 |
-
// typeN: function || object
|
30 |
-
// }
|
31 |
-
// Where if it is a function, it is assumed to be an object constructor that takes the
|
32 |
-
// value of _value as the initialization parameters. If it is an object, then it is assumed
|
33 |
-
// to be an object of general form:
|
34 |
-
// {
|
35 |
-
// type: function, //constructor.
|
36 |
-
// deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
|
37 |
-
// }
|
38 |
-
|
39 |
-
this._arrayOfAllItems = [];
|
40 |
-
this._arrayOfTopLevelItems = [];
|
41 |
-
this._loadFinished = false;
|
42 |
-
this._jsonFileUrl = keywordParameters.url;
|
43 |
-
this._ccUrl = keywordParameters.url;
|
44 |
-
this.url = keywordParameters.url;
|
45 |
-
this._jsonData = keywordParameters.data;
|
46 |
-
this.data = null;
|
47 |
-
this._datatypeMap = keywordParameters.typeMap || {};
|
48 |
-
if(!this._datatypeMap['Date']){
|
49 |
-
//If no default mapping for dates, then set this as default.
|
50 |
-
//We use the dojo.date.stamp here because the ISO format is the 'dojo way'
|
51 |
-
//of generically representing dates.
|
52 |
-
this._datatypeMap['Date'] = {
|
53 |
-
type: Date,
|
54 |
-
deserialize: function(value){
|
55 |
-
return dojo.date.stamp.fromISOString(value);
|
56 |
-
}
|
57 |
-
};
|
58 |
-
}
|
59 |
-
this._features = {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true};
|
60 |
-
this._itemsByIdentity = null;
|
61 |
-
this._storeRefPropName = "_S"; // Default name for the store reference to attach to every item.
|
62 |
-
this._itemNumPropName = "_0"; // Default Item Id for isItem to attach to every item.
|
63 |
-
this._rootItemPropName = "_RI"; // Default Item Id for isItem to attach to every item.
|
64 |
-
this._reverseRefMap = "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity
|
65 |
-
this._loadInProgress = false; //Got to track the initial load to prevent duelling loads of the dataset.
|
66 |
-
this._queuedFetches = [];
|
67 |
-
|
68 |
-
if(keywordParameters.urlPreventCache !== undefined){
|
69 |
-
this.urlPreventCache = keywordParameters.urlPreventCache?true:false;
|
70 |
-
}
|
71 |
-
if(keywordParameters.hierarchical !== undefined){
|
72 |
-
this.hierarchical = keywordParameters.hierarchical?true:false;
|
73 |
-
}
|
74 |
-
if(keywordParameters.clearOnClose){
|
75 |
-
this.clearOnClose = true;
|
76 |
-
}
|
77 |
-
},
|
78 |
-
|
79 |
-
url: "", // use "" rather than undefined for the benefit of the parser (#3539)
|
80 |
-
|
81 |
-
//Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload
|
82 |
-
//when clearOnClose and close is used.
|
83 |
-
_ccUrl: "",
|
84 |
-
|
85 |
-
data: null, //Make this parser settable.
|
86 |
-
|
87 |
-
typeMap: null, //Make this parser settable.
|
88 |
-
|
89 |
-
//Parameter to allow users to specify if a close call should force a reload or not.
|
90 |
-
//By default, it retains the old behavior of not clearing if close is called. But
|
91 |
-
//if set true, the store will be reset to default state. Note that by doing this,
|
92 |
-
//all item handles will become invalid and a new fetch must be issued.
|
93 |
-
clearOnClose: false,
|
94 |
-
|
95 |
-
//Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url.
|
96 |
-
//Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option.
|
97 |
-
//Added for tracker: #6072
|
98 |
-
urlPreventCache: false,
|
99 |
-
|
100 |
-
//Parameter to indicate to process data from the url as hierarchical
|
101 |
-
//(data items can contain other data items in js form). Default is true
|
102 |
-
//for backwards compatibility. False means only root items are processed
|
103 |
-
//as items, all child objects outside of type-mapped objects and those in
|
104 |
-
//specific reference format, are left straight JS data objects.
|
105 |
-
hierarchical: true,
|
106 |
-
|
107 |
-
_assertIsItem: function(/* item */ item){
|
108 |
-
// summary:
|
109 |
-
// This function tests whether the item passed in is indeed an item in the store.
|
110 |
-
// item:
|
111 |
-
// The item to test for being contained by the store.
|
112 |
-
if(!this.isItem(item)){
|
113 |
-
throw new Error("dojox.data.AndOrReadStore: Invalid item argument.");
|
114 |
-
}
|
115 |
-
},
|
116 |
-
|
117 |
-
_assertIsAttribute: function(/* attribute-name-string */ attribute){
|
118 |
-
// summary:
|
119 |
-
// This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
|
120 |
-
// attribute:
|
121 |
-
// The attribute to test for being contained by the store.
|
122 |
-
if(typeof attribute !== "string"){
|
123 |
-
throw new Error("dojox.data.AndOrReadStore: Invalid attribute argument.");
|
124 |
-
}
|
125 |
-
},
|
126 |
-
|
127 |
-
getValue: function( /* item */ item,
|
128 |
-
/* attribute-name-string */ attribute,
|
129 |
-
/* value? */ defaultValue){
|
130 |
-
// summary:
|
131 |
-
// See dojo.data.api.Read.getValue()
|
132 |
-
var values = this.getValues(item, attribute);
|
133 |
-
return (values.length > 0)?values[0]:defaultValue; // mixed
|
134 |
-
},
|
135 |
-
|
136 |
-
getValues: function(/* item */ item,
|
137 |
-
/* attribute-name-string */ attribute){
|
138 |
-
// summary:
|
139 |
-
// See dojo.data.api.Read.getValues()
|
140 |
-
|
141 |
-
this._assertIsItem(item);
|
142 |
-
this._assertIsAttribute(attribute);
|
143 |
-
var arr = item[attribute] || [];
|
144 |
-
// Clone it before returning. refs: #10474
|
145 |
-
return arr.slice(0, arr.length); // Array
|
146 |
-
},
|
147 |
-
|
148 |
-
getAttributes: function(/* item */ item){
|
149 |
-
// summary:
|
150 |
-
// See dojo.data.api.Read.getAttributes()
|
151 |
-
this._assertIsItem(item);
|
152 |
-
var attributes = [];
|
153 |
-
for(var key in item){
|
154 |
-
// Save off only the real item attributes, not the special id marks for O(1) isItem.
|
155 |
-
if((key !== this._storeRefPropName) && (key !== this._itemNumPropName) && (key !== this._rootItemPropName) && (key !== this._reverseRefMap)){
|
156 |
-
attributes.push(key);
|
157 |
-
}
|
158 |
-
}
|
159 |
-
return attributes; // Array
|
160 |
-
},
|
161 |
-
|
162 |
-
hasAttribute: function( /* item */ item,
|
163 |
-
/* attribute-name-string */ attribute){
|
164 |
-
// summary:
|
165 |
-
// See dojo.data.api.Read.hasAttribute()
|
166 |
-
this._assertIsItem(item);
|
167 |
-
this._assertIsAttribute(attribute);
|
168 |
-
return (attribute in item);
|
169 |
-
},
|
170 |
-
|
171 |
-
containsValue: function(/* item */ item,
|
172 |
-
/* attribute-name-string */ attribute,
|
173 |
-
/* anything */ value){
|
174 |
-
// summary:
|
175 |
-
// See dojo.data.api.Read.containsValue()
|
176 |
-
var regexp = undefined;
|
177 |
-
if(typeof value === "string"){
|
178 |
-
regexp = dojo.data.util.filter.patternToRegExp(value, false);
|
179 |
-
}
|
180 |
-
return this._containsValue(item, attribute, value, regexp); //boolean.
|
181 |
-
},
|
182 |
-
|
183 |
-
_containsValue: function( /* item */ item,
|
184 |
-
/* attribute-name-string */ attribute,
|
185 |
-
/* anything */ value,
|
186 |
-
/* RegExp?*/ regexp){
|
187 |
-
// summary:
|
188 |
-
// Internal function for looking at the values contained by the item.
|
189 |
-
// description:
|
190 |
-
// Internal function for looking at the values contained by the item. This
|
191 |
-
// function allows for denoting if the comparison should be case sensitive for
|
192 |
-
// strings or not (for handling filtering cases where string case should not matter)
|
193 |
-
//
|
194 |
-
// item:
|
195 |
-
// The data item to examine for attribute values.
|
196 |
-
// attribute:
|
197 |
-
// The attribute to inspect.
|
198 |
-
// value:
|
199 |
-
// The value to match.
|
200 |
-
// regexp:
|
201 |
-
// Optional regular expression generated off value if value was of string type to handle wildcarding.
|
202 |
-
// If present and attribute values are string, then it can be used for comparison instead of 'value'
|
203 |
-
return dojo.some(this.getValues(item, attribute), function(possibleValue){
|
204 |
-
if(possibleValue !== null && !dojo.isObject(possibleValue) && regexp){
|
205 |
-
if(possibleValue.toString().match(regexp)){
|
206 |
-
return true; // Boolean
|
207 |
-
}
|
208 |
-
}else if(value === possibleValue){
|
209 |
-
return true; // Boolean
|
210 |
-
}
|
211 |
-
});
|
212 |
-
},
|
213 |
-
|
214 |
-
isItem: function(/* anything */ something){
|
215 |
-
// summary:
|
216 |
-
// See dojo.data.api.Read.isItem()
|
217 |
-
if(something && something[this._storeRefPropName] === this){
|
218 |
-
if(this._arrayOfAllItems[something[this._itemNumPropName]] === something){
|
219 |
-
return true;
|
220 |
-
}
|
221 |
-
}
|
222 |
-
return false; // Boolean
|
223 |
-
},
|
224 |
-
|
225 |
-
isItemLoaded: function(/* anything */ something){
|
226 |
-
// summary:
|
227 |
-
// See dojo.data.api.Read.isItemLoaded()
|
228 |
-
return this.isItem(something); //boolean
|
229 |
-
},
|
230 |
-
|
231 |
-
loadItem: function(/* object */ keywordArgs){
|
232 |
-
// summary:
|
233 |
-
// See dojo.data.api.Read.loadItem()
|
234 |
-
this._assertIsItem(keywordArgs.item);
|
235 |
-
},
|
236 |
-
|
237 |
-
getFeatures: function(){
|
238 |
-
// summary:
|
239 |
-
// See dojo.data.api.Read.getFeatures()
|
240 |
-
return this._features; //Object
|
241 |
-
},
|
242 |
-
|
243 |
-
getLabel: function(/* item */ item){
|
244 |
-
// summary:
|
245 |
-
// See dojo.data.api.Read.getLabel()
|
246 |
-
if(this._labelAttr && this.isItem(item)){
|
247 |
-
return this.getValue(item,this._labelAttr); //String
|
248 |
-
}
|
249 |
-
return undefined; //undefined
|
250 |
-
},
|
251 |
-
|
252 |
-
getLabelAttributes: function(/* item */ item){
|
253 |
-
// summary:
|
254 |
-
// See dojo.data.api.Read.getLabelAttributes()
|
255 |
-
if(this._labelAttr){
|
256 |
-
return [this._labelAttr]; //array
|
257 |
-
}
|
258 |
-
return null; //null
|
259 |
-
},
|
260 |
-
|
261 |
-
_fetchItems: function( /* Object */ keywordArgs,
|
262 |
-
/* Function */ findCallback,
|
263 |
-
/* Function */ errorCallback){
|
264 |
-
// summary:
|
265 |
-
// See dojo.data.util.simpleFetch.fetch()
|
266 |
-
// filter modified to permit complex queries where
|
267 |
-
// logical operators are case insensitive:
|
268 |
-
// , NOT AND OR ( ) ! && ||
|
269 |
-
// Note: "," included for quoted/string legacy queries.
|
270 |
-
var self = this;
|
271 |
-
var filter = function(requestArgs, arrayOfItems){
|
272 |
-
var items = [];
|
273 |
-
if(requestArgs.query){
|
274 |
-
//Complete copy, we may have to mess with it.
|
275 |
-
//Safer than clone, which does a shallow copy, I believe.
|
276 |
-
var query = dojo.fromJson(dojo.toJson(requestArgs.query));
|
277 |
-
//Okay, object form query, we have to check to see if someone mixed query methods (such as using FilteringSelect
|
278 |
-
//with a complexQuery). In that case, the params need to be anded to the complex query statement.
|
279 |
-
//See defect #7980
|
280 |
-
if(typeof query == "object" ){
|
281 |
-
var count = 0;
|
282 |
-
var p;
|
283 |
-
for(p in query){
|
284 |
-
count++;
|
285 |
-
}
|
286 |
-
if(count > 1 && query.complexQuery){
|
287 |
-
var cq = query.complexQuery;
|
288 |
-
var wrapped = false;
|
289 |
-
for(p in query){
|
290 |
-
if(p !== "complexQuery"){
|
291 |
-
//We should wrap this in () as it should and with the entire complex query
|
292 |
-
//Not just part of it.
|
293 |
-
if(!wrapped){
|
294 |
-
cq = "( " + cq + " )";
|
295 |
-
wrapped = true;
|
296 |
-
}
|
297 |
-
//Make sure strings are quoted when going into complexQuery merge.
|
298 |
-
var v = requestArgs.query[p];
|
299 |
-
if(dojo.isString(v)){
|
300 |
-
v = "'" + v + "'";
|
301 |
-
}
|
302 |
-
cq += " AND " + p + ":" + v;
|
303 |
-
delete query[p];
|
304 |
-
|
305 |
-
}
|
306 |
-
}
|
307 |
-
query.complexQuery = cq;
|
308 |
-
}
|
309 |
-
}
|
310 |
-
|
311 |
-
var ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false;
|
312 |
-
//for complex queries only: pattern = query[:|=]"NOT id:23* AND (type:'test*' OR dept:'bob') && !filed:true"
|
313 |
-
//logical operators are case insensitive: , NOT AND OR ( ) ! && || // "," included for quoted/string legacy queries.
|
314 |
-
if(typeof query != "string"){
|
315 |
-
query = dojo.toJson(query);
|
316 |
-
query = query.replace(/\\\\/g,"\\"); //counter toJson expansion of backslashes, e.g., foo\\*bar test.
|
317 |
-
}
|
318 |
-
query = query.replace(/\\"/g,"\""); //ditto, for embedded \" in lieu of " availability.
|
319 |
-
var complexQuery = dojo.trim(query.replace(/{|}/g,"")); //we can handle these, too.
|
320 |
-
var pos2, i;
|
321 |
-
if(complexQuery.match(/"? *complexQuery *"?:/)){ //case where widget required a json object, so use complexQuery:'the real query'
|
322 |
-
complexQuery = dojo.trim(complexQuery.replace(/"?\s*complexQuery\s*"?:/,""));
|
323 |
-
var quotes = ["'",'"'];
|
324 |
-
var pos1,colon;
|
325 |
-
var flag = false;
|
326 |
-
for(i = 0; i<quotes.length; i++){
|
327 |
-
pos1 = complexQuery.indexOf(quotes[i]);
|
328 |
-
pos2 = complexQuery.indexOf(quotes[i],1);
|
329 |
-
colon = complexQuery.indexOf(":",1);
|
330 |
-
if(pos1 === 0 && pos2 != -1 && colon < pos2){
|
331 |
-
flag = true;
|
332 |
-
break;
|
333 |
-
} //first two sets of quotes don't occur before the first colon.
|
334 |
-
}
|
335 |
-
if(flag){ //dojo.toJson, and maybe user, adds surrounding quotes, which we need to remove.
|
336 |
-
complexQuery = complexQuery.replace(/^\"|^\'|\"$|\'$/g,"");
|
337 |
-
}
|
338 |
-
} //end query="{complexQuery:'id:1* || dept:Sales'}" parsing (for when widget required json object query).
|
339 |
-
var complexQuerySave = complexQuery;
|
340 |
-
//valid logical operators.
|
341 |
-
var begRegExp = /^,|^NOT |^AND |^OR |^\(|^\)|^!|^&&|^\|\|/i; //trailing space on some tokens on purpose.
|
342 |
-
var sQuery = ""; //will be eval'ed for each i-th candidateItem, based on query components.
|
343 |
-
var op = "";
|
344 |
-
var val = "";
|
345 |
-
var pos = -1;
|
346 |
-
var err = false;
|
347 |
-
var key = "";
|
348 |
-
var value = "";
|
349 |
-
var tok = "";
|
350 |
-
pos2 = -1;
|
351 |
-
for(i = 0; i < arrayOfItems.length; ++i){
|
352 |
-
var match = true;
|
353 |
-
var candidateItem = arrayOfItems[i];
|
354 |
-
if(candidateItem === null){
|
355 |
-
match = false;
|
356 |
-
}else{
|
357 |
-
//process entire string for this i-th candidateItem.
|
358 |
-
complexQuery = complexQuerySave; //restore query for next candidateItem.
|
359 |
-
sQuery = "";
|
360 |
-
//work left to right, finding either key:value pair or logical operator at the beginning of the complexQuery string.
|
361 |
-
//when found, concatenate to sQuery and remove from complexQuery and loop back.
|
362 |
-
while(complexQuery.length > 0 && !err){
|
363 |
-
op = complexQuery.match(begRegExp);
|
364 |
-
|
365 |
-
//get/process/append one or two leading logical operators.
|
366 |
-
while(op && !err){ //look for leading logical operators.
|
367 |
-
complexQuery = dojo.trim(complexQuery.replace(op[0],""));
|
368 |
-
op = dojo.trim(op[0]).toUpperCase();
|
369 |
-
//convert some logical operators to their javascript equivalents for later eval.
|
370 |
-
op = op == "NOT" ? "!" : op == "AND" || op == "," ? "&&" : op == "OR" ? "||" : op;
|
371 |
-
op = " " + op + " ";
|
372 |
-
sQuery += op;
|
373 |
-
op = complexQuery.match(begRegExp);
|
374 |
-
}//end op && !err
|
375 |
-
|
376 |
-
//now get/process/append one key:value pair.
|
377 |
-
if(complexQuery.length > 0){
|
378 |
-
pos = complexQuery.indexOf(":");
|
379 |
-
if(pos == -1){
|
380 |
-
err = true;
|
381 |
-
break;
|
382 |
-
}else{
|
383 |
-
key = dojo.trim(complexQuery.substring(0,pos).replace(/\"|\'/g,""));
|
384 |
-
complexQuery = dojo.trim(complexQuery.substring(pos + 1));
|
385 |
-
tok = complexQuery.match(/^\'|^\"/); //quoted?
|
386 |
-
if(tok){
|
387 |
-
tok = tok[0];
|
388 |
-
pos = complexQuery.indexOf(tok);
|
389 |
-
pos2 = complexQuery.indexOf(tok,pos + 1);
|
390 |
-
if(pos2 == -1){
|
391 |
-
err = true;
|
392 |
-
break;
|
393 |
-
}
|
394 |
-
value = complexQuery.substring(pos + 1,pos2);
|
395 |
-
if(pos2 == complexQuery.length - 1){ //quote is last character
|
396 |
-
complexQuery = "";
|
397 |
-
}else{
|
398 |
-
complexQuery = dojo.trim(complexQuery.substring(pos2 + 1));
|
399 |
-
}
|
400 |
-
sQuery += self._containsValue(candidateItem, key, value, dojo.data.util.filter.patternToRegExp(value, ignoreCase));
|
401 |
-
}
|
402 |
-
else{ //not quoted, so a space, comma, or closing parens (or the end) will be the break.
|
403 |
-
tok = complexQuery.match(/\s|\)|,/);
|
404 |
-
if(tok){
|
405 |
-
var pos3 = new Array(tok.length);
|
406 |
-
for(var j = 0;j<tok.length;j++){
|
407 |
-
pos3[j] = complexQuery.indexOf(tok[j]);
|
408 |
-
}
|
409 |
-
pos = pos3[0];
|
410 |
-
if(pos3.length > 1){
|
411 |
-
for(var j=1;j<pos3.length;j++){
|
412 |
-
pos = Math.min(pos,pos3[j]);
|
413 |
-
}
|
414 |
-
}
|
415 |
-
value = dojo.trim(complexQuery.substring(0,pos));
|
416 |
-
complexQuery = dojo.trim(complexQuery.substring(pos));
|
417 |
-
}else{ //not a space, so must be at the end of the complexQuery.
|
418 |
-
value = dojo.trim(complexQuery);
|
419 |
-
complexQuery = "";
|
420 |
-
} //end inner if(tok) else
|
421 |
-
sQuery += self._containsValue(candidateItem, key, value, dojo.data.util.filter.patternToRegExp(value, ignoreCase));
|
422 |
-
} //end outer if(tok) else
|
423 |
-
} //end found ":"
|
424 |
-
} //end if(complexQuery.length > 0)
|
425 |
-
} //end while complexQuery.length > 0 && !err, so finished the i-th item.
|
426 |
-
|
427 |
-
// BUG: CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
|
428 |
-
// match = eval(sQuery);
|
429 |
-
// FIXED:
|
430 |
-
|
431 |
-
} //end else is non-null candidateItem.
|
432 |
-
if(match){
|
433 |
-
items.push(candidateItem);
|
434 |
-
}
|
435 |
-
} //end for/next of all items.
|
436 |
-
if(err){
|
437 |
-
//soft fail.
|
438 |
-
items = [];
|
439 |
-
console.log("The store's _fetchItems failed, probably due to a syntax error in query.");
|
440 |
-
}
|
441 |
-
findCallback(items, requestArgs);
|
442 |
-
}else{
|
443 |
-
// No query...
|
444 |
-
// We want a copy to pass back in case the parent wishes to sort the array.
|
445 |
-
// We shouldn't allow resort of the internal list, so that multiple callers
|
446 |
-
// can get lists and sort without affecting each other. We also need to
|
447 |
-
// filter out any null values that have been left as a result of deleteItem()
|
448 |
-
// calls in ItemFileWriteStore.
|
449 |
-
for(var i = 0; i < arrayOfItems.length; ++i){
|
450 |
-
var item = arrayOfItems[i];
|
451 |
-
if(item !== null){
|
452 |
-
items.push(item);
|
453 |
-
}
|
454 |
-
}
|
455 |
-
findCallback(items, requestArgs);
|
456 |
-
} //end if there is a query.
|
457 |
-
}; //end filter function
|
458 |
-
|
459 |
-
if(this._loadFinished){
|
460 |
-
filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
|
461 |
-
}else{
|
462 |
-
if(this._jsonFileUrl !== this._ccUrl){
|
463 |
-
dojo.deprecated("dojox.data.AndOrReadStore: ",
|
464 |
-
"To change the url, set the url property of the store," +
|
465 |
-
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
|
466 |
-
this._ccUrl = this._jsonFileUrl;
|
467 |
-
this.url = this._jsonFileUrl;
|
468 |
-
}else if(this.url !== this._ccUrl){
|
469 |
-
this._jsonFileUrl = this.url;
|
470 |
-
this._ccUrl = this.url;
|
471 |
-
}
|
472 |
-
//See if there was any forced reset of data.
|
473 |
-
if(this.data != null && this._jsonData == null){
|
474 |
-
this._jsonData = this.data;
|
475 |
-
this.data = null;
|
476 |
-
}
|
477 |
-
if(this._jsonFileUrl){
|
478 |
-
//If fetches come in before the loading has finished, but while
|
479 |
-
//a load is in progress, we have to defer the fetching to be
|
480 |
-
//invoked in the callback.
|
481 |
-
if(this._loadInProgress){
|
482 |
-
this._queuedFetches.push({args: keywordArgs, filter: filter});
|
483 |
-
}else{
|
484 |
-
this._loadInProgress = true;
|
485 |
-
var getArgs = {
|
486 |
-
url: self._jsonFileUrl,
|
487 |
-
handleAs: "json-comment-optional",
|
488 |
-
preventCache: this.urlPreventCache
|
489 |
-
};
|
490 |
-
var getHandler = dojo.xhrGet(getArgs);
|
491 |
-
getHandler.addCallback(function(data){
|
492 |
-
try{
|
493 |
-
self._getItemsFromLoadedData(data);
|
494 |
-
self._loadFinished = true;
|
495 |
-
self._loadInProgress = false;
|
496 |
-
|
497 |
-
filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
|
498 |
-
self._handleQueuedFetches();
|
499 |
-
}catch(e){
|
500 |
-
self._loadFinished = true;
|
501 |
-
self._loadInProgress = false;
|
502 |
-
errorCallback(e, keywordArgs);
|
503 |
-
}
|
504 |
-
});
|
505 |
-
getHandler.addErrback(function(error){
|
506 |
-
self._loadInProgress = false;
|
507 |
-
errorCallback(error, keywordArgs);
|
508 |
-
});
|
509 |
-
|
510 |
-
//Wire up the cancel to abort of the request
|
511 |
-
//This call cancel on the deferred if it hasn't been called
|
512 |
-
//yet and then will chain to the simple abort of the
|
513 |
-
//simpleFetch keywordArgs
|
514 |
-
var oldAbort = null;
|
515 |
-
if(keywordArgs.abort){
|
516 |
-
oldAbort = keywordArgs.abort;
|
517 |
-
}
|
518 |
-
keywordArgs.abort = function(){
|
519 |
-
var df = getHandler;
|
520 |
-
if(df && df.fired === -1){
|
521 |
-
df.cancel();
|
522 |
-
df = null;
|
523 |
-
}
|
524 |
-
if(oldAbort){
|
525 |
-
oldAbort.call(keywordArgs);
|
526 |
-
}
|
527 |
-
};
|
528 |
-
}
|
529 |
-
}else if(this._jsonData){
|
530 |
-
try{
|
531 |
-
this._loadFinished = true;
|
532 |
-
this._getItemsFromLoadedData(this._jsonData);
|
533 |
-
this._jsonData = null;
|
534 |
-
filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
|
535 |
-
}catch(e){
|
536 |
-
errorCallback(e, keywordArgs);
|
537 |
-
}
|
538 |
-
}else{
|
539 |
-
errorCallback(new Error("dojox.data.AndOrReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs);
|
540 |
-
}
|
541 |
-
} //end deferred fetching.
|
542 |
-
}, //end _fetchItems
|
543 |
-
|
544 |
-
_handleQueuedFetches: function(){
|
545 |
-
// summary:
|
546 |
-
// Internal function to execute delayed request in the store.
|
547 |
-
//Execute any deferred fetches now.
|
548 |
-
if(this._queuedFetches.length > 0){
|
549 |
-
for(var i = 0; i < this._queuedFetches.length; i++){
|
550 |
-
var fData = this._queuedFetches[i];
|
551 |
-
var delayedQuery = fData.args;
|
552 |
-
var delayedFilter = fData.filter;
|
553 |
-
if(delayedFilter){
|
554 |
-
delayedFilter(delayedQuery, this._getItemsArray(delayedQuery.queryOptions));
|
555 |
-
}else{
|
556 |
-
this.fetchItemByIdentity(delayedQuery);
|
557 |
-
}
|
558 |
-
}
|
559 |
-
this._queuedFetches = [];
|
560 |
-
}
|
561 |
-
},
|
562 |
-
|
563 |
-
_getItemsArray: function(/*object?*/queryOptions){
|
564 |
-
// summary:
|
565 |
-
// Internal function to determine which list of items to search over.
|
566 |
-
// queryOptions: The query options parameter, if any.
|
567 |
-
if(queryOptions && queryOptions.deep){
|
568 |
-
return this._arrayOfAllItems;
|
569 |
-
}
|
570 |
-
return this._arrayOfTopLevelItems;
|
571 |
-
},
|
572 |
-
|
573 |
-
close: function(/*dojo.data.api.Request || keywordArgs || null */ request){
|
574 |
-
// summary:
|
575 |
-
// See dojo.data.api.Read.close()
|
576 |
-
if(this.clearOnClose &&
|
577 |
-
this._loadFinished &&
|
578 |
-
!this._loadInProgress){
|
579 |
-
//Reset all internalsback to default state. This will force a reload
|
580 |
-
//on next fetch. This also checks that the data or url param was set
|
581 |
-
//so that the store knows it can get data. Without one of those being set,
|
582 |
-
//the next fetch will trigger an error.
|
583 |
-
|
584 |
-
if(((this._jsonFileUrl == "" || this._jsonFileUrl == null) &&
|
585 |
-
(this.url == "" || this.url == null)
|
586 |
-
) && this.data == null){
|
587 |
-
console.debug("dojox.data.AndOrReadStore: WARNING! Data reload " +
|
588 |
-
" information has not been provided." +
|
589 |
-
" Please set 'url' or 'data' to the appropriate value before" +
|
590 |
-
" the next fetch");
|
591 |
-
}
|
592 |
-
this._arrayOfAllItems = [];
|
593 |
-
this._arrayOfTopLevelItems = [];
|
594 |
-
this._loadFinished = false;
|
595 |
-
this._itemsByIdentity = null;
|
596 |
-
this._loadInProgress = false;
|
597 |
-
this._queuedFetches = [];
|
598 |
-
}
|
599 |
-
},
|
600 |
-
|
601 |
-
_getItemsFromLoadedData: function(/* Object */ dataObject){
|
602 |
-
// summary:
|
603 |
-
// Function to parse the loaded data into item format and build the internal items array.
|
604 |
-
// description:
|
605 |
-
// Function to parse the loaded data into item format and build the internal items array.
|
606 |
-
//
|
607 |
-
// dataObject:
|
608 |
-
// The JS data object containing the raw data to convery into item format.
|
609 |
-
//
|
610 |
-
// returns: array
|
611 |
-
// Array of items in store item format.
|
612 |
-
|
613 |
-
// First, we define a couple little utility functions...
|
614 |
-
|
615 |
-
var self = this;
|
616 |
-
function valueIsAnItem(/* anything */ aValue){
|
617 |
-
// summary:
|
618 |
-
// Given any sort of value that could be in the raw json data,
|
619 |
-
// return true if we should interpret the value as being an
|
620 |
-
// item itself, rather than a literal value or a reference.
|
621 |
-
// example:
|
622 |
-
// | false == valueIsAnItem("Kermit");
|
623 |
-
// | false == valueIsAnItem(42);
|
624 |
-
// | false == valueIsAnItem(new Date());
|
625 |
-
// | false == valueIsAnItem({_type:'Date', _value:'May 14, 1802'});
|
626 |
-
// | false == valueIsAnItem({_reference:'Kermit'});
|
627 |
-
// | true == valueIsAnItem({name:'Kermit', color:'green'});
|
628 |
-
// | true == valueIsAnItem({iggy:'pop'});
|
629 |
-
// | true == valueIsAnItem({foo:42});
|
630 |
-
var isItem = (
|
631 |
-
(aValue !== null) &&
|
632 |
-
(typeof aValue === "object") &&
|
633 |
-
(!dojo.isArray(aValue)) &&
|
634 |
-
(!dojo.isFunction(aValue)) &&
|
635 |
-
(aValue.constructor == Object) &&
|
636 |
-
(typeof aValue._reference === "undefined") &&
|
637 |
-
(typeof aValue._type === "undefined") &&
|
638 |
-
(typeof aValue._value === "undefined") &&
|
639 |
-
self.hierarchical
|
640 |
-
);
|
641 |
-
return isItem;
|
642 |
-
}
|
643 |
-
|
644 |
-
function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem){
|
645 |
-
self._arrayOfAllItems.push(anItem);
|
646 |
-
for(var attribute in anItem){
|
647 |
-
var valueForAttribute = anItem[attribute];
|
648 |
-
if(valueForAttribute){
|
649 |
-
if(dojo.isArray(valueForAttribute)){
|
650 |
-
var valueArray = valueForAttribute;
|
651 |
-
for(var k = 0; k < valueArray.length; ++k){
|
652 |
-
var singleValue = valueArray[k];
|
653 |
-
if(valueIsAnItem(singleValue)){
|
654 |
-
addItemAndSubItemsToArrayOfAllItems(singleValue);
|
655 |
-
}
|
656 |
-
}
|
657 |
-
}else{
|
658 |
-
if(valueIsAnItem(valueForAttribute)){
|
659 |
-
addItemAndSubItemsToArrayOfAllItems(valueForAttribute);
|
660 |
-
}
|
661 |
-
}
|
662 |
-
}
|
663 |
-
}
|
664 |
-
}
|
665 |
-
|
666 |
-
this._labelAttr = dataObject.label;
|
667 |
-
|
668 |
-
// We need to do some transformations to convert the data structure
|
669 |
-
// that we read from the file into a format that will be convenient
|
670 |
-
// to work with in memory.
|
671 |
-
|
672 |
-
// Step 1: Walk through the object hierarchy and build a list of all items
|
673 |
-
var i;
|
674 |
-
var item;
|
675 |
-
this._arrayOfAllItems = [];
|
676 |
-
this._arrayOfTopLevelItems = dataObject.items;
|
677 |
-
|
678 |
-
for(i = 0; i < this._arrayOfTopLevelItems.length; ++i){
|
679 |
-
item = this._arrayOfTopLevelItems[i];
|
680 |
-
addItemAndSubItemsToArrayOfAllItems(item);
|
681 |
-
item[this._rootItemPropName]=true;
|
682 |
-
}
|
683 |
-
|
684 |
-
// Step 2: Walk through all the attribute values of all the items,
|
685 |
-
// and replace single values with arrays. For example, we change this:
|
686 |
-
// { name:'Miss Piggy', pets:'Foo-Foo'}
|
687 |
-
// into this:
|
688 |
-
// { name:['Miss Piggy'], pets:['Foo-Foo']}
|
689 |
-
//
|
690 |
-
// We also store the attribute names so we can validate our store
|
691 |
-
// reference and item id special properties for the O(1) isItem
|
692 |
-
var allAttributeNames = {};
|
693 |
-
var key;
|
694 |
-
|
695 |
-
for(i = 0; i < this._arrayOfAllItems.length; ++i){
|
696 |
-
item = this._arrayOfAllItems[i];
|
697 |
-
for(key in item){
|
698 |
-
if(key !== this._rootItemPropName){
|
699 |
-
var value = item[key];
|
700 |
-
if(value !== null){
|
701 |
-
if(!dojo.isArray(value)){
|
702 |
-
item[key] = [value];
|
703 |
-
}
|
704 |
-
}else{
|
705 |
-
item[key] = [null];
|
706 |
-
}
|
707 |
-
}
|
708 |
-
allAttributeNames[key]=key;
|
709 |
-
}
|
710 |
-
}
|
711 |
-
|
712 |
-
// Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName
|
713 |
-
// This should go really fast, it will generally never even run the loop.
|
714 |
-
while(allAttributeNames[this._storeRefPropName]){
|
715 |
-
this._storeRefPropName += "_";
|
716 |
-
}
|
717 |
-
while(allAttributeNames[this._itemNumPropName]){
|
718 |
-
this._itemNumPropName += "_";
|
719 |
-
}
|
720 |
-
while(allAttributeNames[this._reverseRefMap]){
|
721 |
-
this._reverseRefMap += "_";
|
722 |
-
}
|
723 |
-
|
724 |
-
// Step 4: Some data files specify an optional 'identifier', which is
|
725 |
-
// the name of an attribute that holds the identity of each item.
|
726 |
-
// If this data file specified an identifier attribute, then build a
|
727 |
-
// hash table of items keyed by the identity of the items.
|
728 |
-
var arrayOfValues;
|
729 |
-
|
730 |
-
var identifier = dataObject.identifier;
|
731 |
-
if(identifier){
|
732 |
-
this._itemsByIdentity = {};
|
733 |
-
this._features['dojo.data.api.Identity'] = identifier;
|
734 |
-
for(i = 0; i < this._arrayOfAllItems.length; ++i){
|
735 |
-
item = this._arrayOfAllItems[i];
|
736 |
-
arrayOfValues = item[identifier];
|
737 |
-
var identity = arrayOfValues[0];
|
738 |
-
if(!this._itemsByIdentity[identity]){
|
739 |
-
this._itemsByIdentity[identity] = item;
|
740 |
-
}else{
|
741 |
-
if(this._jsonFileUrl){
|
742 |
-
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 + "]");
|
743 |
-
}else if(this._jsonData){
|
744 |
-
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 + "]");
|
745 |
-
}
|
746 |
-
}
|
747 |
-
}
|
748 |
-
}else{
|
749 |
-
this._features['dojo.data.api.Identity'] = Number;
|
750 |
-
}
|
751 |
-
|
752 |
-
// Step 5: Walk through all the items, and set each item's properties
|
753 |
-
// for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true.
|
754 |
-
for(i = 0; i < this._arrayOfAllItems.length; ++i){
|
755 |
-
item = this._arrayOfAllItems[i];
|
756 |
-
item[this._storeRefPropName] = this;
|
757 |
-
item[this._itemNumPropName] = i;
|
758 |
-
}
|
759 |
-
|
760 |
-
// Step 6: We walk through all the attribute values of all the items,
|
761 |
-
// looking for type/value literals and item-references.
|
762 |
-
//
|
763 |
-
// We replace item-references with pointers to items. For example, we change:
|
764 |
-
// { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
|
765 |
-
// into this:
|
766 |
-
// { name:['Kermit'], friends:[miss_piggy] }
|
767 |
-
// (where miss_piggy is the object representing the 'Miss Piggy' item).
|
768 |
-
//
|
769 |
-
// We replace type/value pairs with typed-literals. For example, we change:
|
770 |
-
// { name:['Nelson Mandela'], born:[{_type:'Date', _value:'July 18, 1918'}] }
|
771 |
-
// into this:
|
772 |
-
// { name:['Kermit'], born:(new Date('July 18, 1918')) }
|
773 |
-
//
|
774 |
-
// We also generate the associate map for all items for the O(1) isItem function.
|
775 |
-
for(i = 0; i < this._arrayOfAllItems.length; ++i){
|
776 |
-
item = this._arrayOfAllItems[i]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
|
777 |
-
for(key in item){
|
778 |
-
arrayOfValues = item[key]; // example: [{_reference:{name:'Miss Piggy'}}]
|
779 |
-
for(var j = 0; j < arrayOfValues.length; ++j){
|
780 |
-
value = arrayOfValues[j]; // example: {_reference:{name:'Miss Piggy'}}
|
781 |
-
if(value !== null && typeof value == "object"){
|
782 |
-
if(("_type" in value) && ("_value" in value)){
|
783 |
-
var type = value._type; // examples: 'Date', 'Color', or 'ComplexNumber'
|
784 |
-
var mappingObj = this._datatypeMap[type]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}}
|
785 |
-
if(!mappingObj){
|
786 |
-
throw new Error("dojox.data.AndOrReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type + "'");
|
787 |
-
}else if(dojo.isFunction(mappingObj)){
|
788 |
-
arrayOfValues[j] = new mappingObj(value._value);
|
789 |
-
}else if(dojo.isFunction(mappingObj.deserialize)){
|
790 |
-
arrayOfValues[j] = mappingObj.deserialize(value._value);
|
791 |
-
}else{
|
792 |
-
throw new Error("dojox.data.AndOrReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");
|
793 |
-
}
|
794 |
-
}
|
795 |
-
if(value._reference){
|
796 |
-
var referenceDescription = value._reference; // example: {name:'Miss Piggy'}
|
797 |
-
if(!dojo.isObject(referenceDescription)){
|
798 |
-
// example: 'Miss Piggy'
|
799 |
-
// from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]}
|
800 |
-
arrayOfValues[j] = this._getItemByIdentity(referenceDescription);
|
801 |
-
}else{
|
802 |
-
// example: {name:'Miss Piggy'}
|
803 |
-
// from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
|
804 |
-
for(var k = 0; k < this._arrayOfAllItems.length; ++k){
|
805 |
-
var candidateItem = this._arrayOfAllItems[k];
|
806 |
-
var found = true;
|
807 |
-
for(var refKey in referenceDescription){
|
808 |
-
if(candidateItem[refKey] != referenceDescription[refKey]){
|
809 |
-
found = false;
|
810 |
-
}
|
811 |
-
}
|
812 |
-
if(found){
|
813 |
-
arrayOfValues[j] = candidateItem;
|
814 |
-
}
|
815 |
-
}
|
816 |
-
}
|
817 |
-
if(this.referenceIntegrity){
|
818 |
-
var refItem = arrayOfValues[j];
|
819 |
-
if(this.isItem(refItem)){
|
820 |
-
this._addReferenceToMap(refItem, item, key);
|
821 |
-
}
|
822 |
-
}
|
823 |
-
}else if(this.isItem(value)){
|
824 |
-
//It's a child item (not one referenced through _reference).
|
825 |
-
//We need to treat this as a referenced item, so it can be cleaned up
|
826 |
-
//in a write store easily.
|
827 |
-
if(this.referenceIntegrity){
|
828 |
-
this._addReferenceToMap(value, item, key);
|
829 |
-
}
|
830 |
-
}
|
831 |
-
}
|
832 |
-
}
|
833 |
-
}
|
834 |
-
}
|
835 |
-
},
|
836 |
-
|
837 |
-
_addReferenceToMap: function(/*item*/ refItem, /*item*/ parentItem, /*string*/ attribute){
|
838 |
-
// summary:
|
839 |
-
// Method to add an reference map entry for an item and attribute.
|
840 |
-
// description:
|
841 |
-
// Method to add an reference map entry for an item and attribute. //
|
842 |
-
// refItem:
|
843 |
-
// The item that is referenced.
|
844 |
-
// parentItem:
|
845 |
-
// The item that holds the new reference to refItem.
|
846 |
-
// attribute:
|
847 |
-
// The attribute on parentItem that contains the new reference.
|
848 |
-
|
849 |
-
//Stub function, does nothing. Real processing is in ItemFileWriteStore.
|
850 |
-
},
|
851 |
-
|
852 |
-
getIdentity: function(/* item */ item){
|
853 |
-
// summary:
|
854 |
-
// See dojo.data.api.Identity.getIdentity()
|
855 |
-
var identifier = this._features['dojo.data.api.Identity'];
|
856 |
-
if(identifier === Number){
|
857 |
-
return item[this._itemNumPropName]; // Number
|
858 |
-
}else{
|
859 |
-
var arrayOfValues = item[identifier];
|
860 |
-
if(arrayOfValues){
|
861 |
-
return arrayOfValues[0]; // Object || String
|
862 |
-
}
|
863 |
-
}
|
864 |
-
return null; // null
|
865 |
-
},
|
866 |
-
|
867 |
-
fetchItemByIdentity: function(/* Object */ keywordArgs){
|
868 |
-
// summary:
|
869 |
-
// See dojo.data.api.Identity.fetchItemByIdentity()
|
870 |
-
|
871 |
-
// Hasn't loaded yet, we have to trigger the load.
|
872 |
-
if(!this._loadFinished){
|
873 |
-
var self = this;
|
874 |
-
if(this._jsonFileUrl !== this._ccUrl){
|
875 |
-
dojo.deprecated("dojox.data.AndOrReadStore: ",
|
876 |
-
"To change the url, set the url property of the store," +
|
877 |
-
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
|
878 |
-
this._ccUrl = this._jsonFileUrl;
|
879 |
-
this.url = this._jsonFileUrl;
|
880 |
-
}else if(this.url !== this._ccUrl){
|
881 |
-
this._jsonFileUrl = this.url;
|
882 |
-
this._ccUrl = this.url;
|
883 |
-
}
|
884 |
-
//See if there was any forced reset of data.
|
885 |
-
if(this.data != null && this._jsonData == null){
|
886 |
-
this._jsonData = this.data;
|
887 |
-
this.data = null;
|
888 |
-
}
|
889 |
-
if(this._jsonFileUrl){
|
890 |
-
|
891 |
-
if(this._loadInProgress){
|
892 |
-
this._queuedFetches.push({args: keywordArgs});
|
893 |
-
}else{
|
894 |
-
this._loadInProgress = true;
|
895 |
-
var getArgs = {
|
896 |
-
url: self._jsonFileUrl,
|
897 |
-
handleAs: "json-comment-optional",
|
898 |
-
preventCache: this.urlPreventCache
|
899 |
-
};
|
900 |
-
var getHandler = dojo.xhrGet(getArgs);
|
901 |
-
getHandler.addCallback(function(data){
|
902 |
-
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
|
903 |
-
try{
|
904 |
-
self._getItemsFromLoadedData(data);
|
905 |
-
self._loadFinished = true;
|
906 |
-
self._loadInProgress = false;
|
907 |
-
var item = self._getItemByIdentity(keywordArgs.identity);
|
908 |
-
if(keywordArgs.onItem){
|
909 |
-
keywordArgs.onItem.call(scope, item);
|
910 |
-
}
|
911 |
-
self._handleQueuedFetches();
|
912 |
-
}catch(error){
|
913 |
-
self._loadInProgress = false;
|
914 |
-
if(keywordArgs.onError){
|
915 |
-
keywordArgs.onError.call(scope, error);
|
916 |
-
}
|
917 |
-
}
|
918 |
-
});
|
919 |
-
getHandler.addErrback(function(error){
|
920 |
-
self._loadInProgress = false;
|
921 |
-
if(keywordArgs.onError){
|
922 |
-
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
|
923 |
-
keywordArgs.onError.call(scope, error);
|
924 |
-
}
|
925 |
-
});
|
926 |
-
}
|
927 |
-
|
928 |
-
}else if(this._jsonData){
|
929 |
-
// Passed in data, no need to xhr.
|
930 |
-
self._getItemsFromLoadedData(self._jsonData);
|
931 |
-
self._jsonData = null;
|
932 |
-
self._loadFinished = true;
|
933 |
-
var item = self._getItemByIdentity(keywordArgs.identity);
|
934 |
-
if(keywordArgs.onItem){
|
935 |
-
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
|
936 |
-
keywordArgs.onItem.call(scope, item);
|
937 |
-
}
|
938 |
-
}
|
939 |
-
}else{
|
940 |
-
// Already loaded. We can just look it up and call back.
|
941 |
-
var item = this._getItemByIdentity(keywordArgs.identity);
|
942 |
-
if(keywordArgs.onItem){
|
943 |
-
var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
|
944 |
-
keywordArgs.onItem.call(scope, item);
|
945 |
-
}
|
946 |
-
}
|
947 |
-
},
|
948 |
-
|
949 |
-
_getItemByIdentity: function(/* Object */ identity){
|
950 |
-
// summary:
|
951 |
-
// Internal function to look an item up by its identity map.
|
952 |
-
var item = null;
|
953 |
-
if(this._itemsByIdentity){
|
954 |
-
item = this._itemsByIdentity[identity];
|
955 |
-
}else{
|
956 |
-
item = this._arrayOfAllItems[identity];
|
957 |
-
}
|
958 |
-
if(item === undefined){
|
959 |
-
item = null;
|
960 |
-
}
|
961 |
-
return item; // Object
|
962 |
-
},
|
963 |
-
|
964 |
-
getIdentityAttributes: function(/* item */ item){
|
965 |
-
// summary:
|
966 |
-
// See dojo.data.api.Identity.getIdentifierAttributes()
|
967 |
-
|
968 |
-
var identifier = this._features['dojo.data.api.Identity'];
|
969 |
-
if(identifier === Number){
|
970 |
-
// If (identifier === Number) it means getIdentity() just returns
|
971 |
-
// an integer item-number for each item. The dojo.data.api.Identity
|
972 |
-
// spec says we need to return null if the identity is not composed
|
973 |
-
// of attributes
|
974 |
-
return null; // null
|
975 |
-
}else{
|
976 |
-
return [identifier]; // Array
|
977 |
-
}
|
978 |
-
},
|
979 |
-
|
980 |
-
_forceLoad: function(){
|
981 |
-
// summary:
|
982 |
-
// Internal function to force a load of the store if it hasn't occurred yet. This is required
|
983 |
-
// for specific functions to work properly.
|
984 |
-
var self = this;
|
985 |
-
if(this._jsonFileUrl !== this._ccUrl){
|
986 |
-
dojo.deprecated("dojox.data.AndOrReadStore: ",
|
987 |
-
"To change the url, set the url property of the store," +
|
988 |
-
" not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
|
989 |
-
this._ccUrl = this._jsonFileUrl;
|
990 |
-
this.url = this._jsonFileUrl;
|
991 |
-
}else if(this.url !== this._ccUrl){
|
992 |
-
this._jsonFileUrl = this.url;
|
993 |
-
this._ccUrl = this.url;
|
994 |
-
}
|
995 |
-
//See if there was any forced reset of data.
|
996 |
-
if(this.data != null && this._jsonData == null){
|
997 |
-
this._jsonData = this.data;
|
998 |
-
this.data = null;
|
999 |
-
}
|
1000 |
-
if(this._jsonFileUrl){
|
1001 |
-
var getArgs = {
|
1002 |
-
url: self._jsonFileUrl,
|
1003 |
-
handleAs: "json-comment-optional",
|
1004 |
-
preventCache: this.urlPreventCache,
|
1005 |
-
sync: true
|
1006 |
-
};
|
1007 |
-
var getHandler = dojo.xhrGet(getArgs);
|
1008 |
-
getHandler.addCallback(function(data){
|
1009 |
-
try{
|
1010 |
-
//Check to be sure there wasn't another load going on concurrently
|
1011 |
-
//So we don't clobber data that comes in on it. If there is a load going on
|
1012 |
-
//then do not save this data. It will potentially clobber current data.
|
1013 |
-
//We mainly wanted to sync/wait here.
|
1014 |
-
//TODO: Revisit the loading scheme of this store to improve multi-initial
|
1015 |
-
//request handling.
|
1016 |
-
if(self._loadInProgress !== true && !self._loadFinished){
|
1017 |
-
self._getItemsFromLoadedData(data);
|
1018 |
-
self._loadFinished = true;
|
1019 |
-
}else if(self._loadInProgress){
|
1020 |
-
//Okay, we hit an error state we can't recover from. A forced load occurred
|
1021 |
-
//while an async load was occurring. Since we cannot block at this point, the best
|
1022 |
-
//that can be managed is to throw an error.
|
1023 |
-
throw new Error("dojox.data.AndOrReadStore: Unable to perform a synchronous load, an async load is in progress.");
|
1024 |
-
}
|
1025 |
-
}catch(e){
|
1026 |
-
console.log(e);
|
1027 |
-
throw e;
|
1028 |
-
}
|
1029 |
-
});
|
1030 |
-
getHandler.addErrback(function(error){
|
1031 |
-
throw error;
|
1032 |
-
});
|
1033 |
-
}else if(this._jsonData){
|
1034 |
-
self._getItemsFromLoadedData(self._jsonData);
|
1035 |
-
self._jsonData = null;
|
1036 |
-
self._loadFinished = true;
|
1037 |
-
}
|
1038 |
-
}
|
1039 |
-
});
|
1040 |
-
//Mix in the simple fetch implementation to this class.
|
1041 |
-
dojo.extend(dojox.data.AndOrReadStore,dojo.data.util.simpleFetch);
|
1042 |
-
|
1043 |
-
return dojox.data.AndOrReadStore;
|
1044 |
-
});
|
1045 |
-
|
1046 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/13.js
DELETED
The diff for this file is too large to render.
See raw diff
|
|
data/javaScript/130.js
DELETED
@@ -1,92 +0,0 @@
|
|
1 |
-
(function(){
|
2 |
-
var file;
|
3 |
-
var head = document.documentElement.firstChild;
|
4 |
-
while(head && head.tagName != "HEAD"){
|
5 |
-
head = head.nextSibling;
|
6 |
-
}
|
7 |
-
var script = head.lastChild;
|
8 |
-
while(script){
|
9 |
-
if(script.tagName == "SCRIPT"){
|
10 |
-
if((script.getAttribute('src')||'').search('_loadTest') >= 0 && (!script.readyState || script.readyState == "interactive")){
|
11 |
-
file = script.getAttribute('file');
|
12 |
-
break;
|
13 |
-
}
|
14 |
-
}
|
15 |
-
script = script.previousSibling;
|
16 |
-
}
|
17 |
-
if(!file && window.location.href.search(/[?&]file[=]/i) > 0){
|
18 |
-
file = window.location.href.replace(/.*[?&]file=(([^&?]*)).*/i, "$2");
|
19 |
-
}
|
20 |
-
var readFile = function(file){
|
21 |
-
var xhr = null;
|
22 |
-
try{ xhr = new XMLHttpRequest() }catch(e0){
|
23 |
-
try{ xhr = new ActiveXObject('Msxml2.XMLHTTP') }catch(e1){
|
24 |
-
try{ xhr = new ActiveXObject('Microsoft.XMLHTTP') }catch(e2){
|
25 |
-
try{ xhr = new ActiveXObject('Msxml2.XMLHTTP.4.0') }catch(e3){}}}}
|
26 |
-
try{
|
27 |
-
xhr.open("GET", file, false);
|
28 |
-
xhr.send(null);
|
29 |
-
}catch(e){ return null } // file not found
|
30 |
-
return xhr.responseText;
|
31 |
-
}
|
32 |
-
var text = readFile(file) || (file + " not found");
|
33 |
-
var baseHref = file.replace(/^(.*\/)?[^\/]+$/, "$1");
|
34 |
-
if(baseHref){
|
35 |
-
baseHref = window.location.href.replace(/[?].*/, "").replace(/[^\/]*$/, "")+baseHref;
|
36 |
-
|
37 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
38 |
-
// text = text.replace(/(<HEAD\b([^>]|\s)*>)/i, "$1" + "<BASE href='" + baseHref + "'><\/BASE>");
|
39 |
-
// FIXED:
|
40 |
-
|
41 |
-
}
|
42 |
-
// strip DOCTYPE and HTML tag
|
43 |
-
text = text.replace(/^(.|\s)*?<html\b(([^>]|\s)*)>((.|\s)*)/i,
|
44 |
-
function(s,a1,htmlAttrs,a3,content){
|
45 |
-
// add attributes from target file's HTML tag - may not be necessary but we'll do it anyway for completeness
|
46 |
-
htmlAttrs = htmlAttrs.replace(/((\w+)\s*=\s*(['"]?)(.*?)(\3)?(\s+|$))/g,
|
47 |
-
function(s, all, attr, quote, val){
|
48 |
-
document.documentElement.setAttribute(attr, val);
|
49 |
-
return "";
|
50 |
-
});
|
51 |
-
return content.replace(/<\/html\b([^>]|\s)*>(.|\s)*?$/i, "");
|
52 |
-
});
|
53 |
-
if(/MSIE/.test(navigator.userAgent)){ // need to load scripts serially
|
54 |
-
document._oldgetElementsByTagName_ = document.getElementsByTagName;
|
55 |
-
document.getElementsByTagName = function(tag){
|
56 |
-
// take over getElementsByTagName so I can take over script.getAttribute('src')
|
57 |
-
if(/^script$/i.test(tag)){
|
58 |
-
var scripts = document.scripts;
|
59 |
-
for(var i=0; i <scripts.length; i++){
|
60 |
-
var script = scripts[i];
|
61 |
-
if(!script['_oldGetAttribute']){
|
62 |
-
var src = script.getAttribute('_oldsrc');
|
63 |
-
if(src){
|
64 |
-
script._oldGetAttribute = script.getAttribute;
|
65 |
-
script.getAttribute = function(attr){ if(/^src$/i.test(attr))attr='_oldsrc';return script._oldGetAttribute(attr) };
|
66 |
-
}
|
67 |
-
}
|
68 |
-
}
|
69 |
-
return scripts;
|
70 |
-
}
|
71 |
-
return document._oldgetElementsByTagName_(tag);
|
72 |
-
};
|
73 |
-
document._oldwrite_ = document.write;
|
74 |
-
document.write = function(text){
|
75 |
-
text = text.replace(/<[!][-][-](.|\s){5,}?[-][-]>/g, "<!--?-->" // shorten long comments that may contain script tags
|
76 |
-
).replace(/(<script\s[^>]*)\bsrc\s*=\s*([^>]*>)/ig,
|
77 |
-
function(s,pre,post){
|
78 |
-
if(s.search(/\sdefer\b/i) > 0){ return s; }
|
79 |
-
//if(s.search(/\bxpopup.js\b/i) > 0){ return pre+">"; } // firewall popup blocker: uncomment if you get out of stack space message
|
80 |
-
var file = post.substr(0, post.search(/\s|>/)).replace(/['"]/g, "");
|
81 |
-
var scriptText = readFile(baseHref+file);
|
82 |
-
if(!scriptText){
|
83 |
-
scriptText = readFile(file);
|
84 |
-
if(!scriptText){ return s; }
|
85 |
-
}
|
86 |
-
return pre + " _oldsrc=" + post + "eval(unescape('"+escape(scriptText)+"'))";
|
87 |
-
});
|
88 |
-
document._oldwrite_(text);
|
89 |
-
};
|
90 |
-
}
|
91 |
-
document.write(text);
|
92 |
-
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/131.js
DELETED
@@ -1,131 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
_testCommon.js - a simple module to be included in dijit test pages to allow
|
3 |
-
for easy switching between the many many points of the test-matrix.
|
4 |
-
|
5 |
-
in your test browser, provides a way to switch between available themes,
|
6 |
-
and optionally enable RTL (right to left) mode, and/or dijit_a11y (high-
|
7 |
-
constrast/image off emulation) ... probably not a genuine test for a11y.
|
8 |
-
|
9 |
-
usage: on any dijit test_* page, press ctrl-f9 to popup links.
|
10 |
-
|
11 |
-
there are currently (3 themes * 4 tests) * (10 variations of supported browsers)
|
12 |
-
not including testing individual locale-strings
|
13 |
-
|
14 |
-
you should NOT be using this in a production environment. include
|
15 |
-
your css and set your classes manually. for test purposes only ...
|
16 |
-
*/
|
17 |
-
|
18 |
-
(function(){
|
19 |
-
var d = dojo,
|
20 |
-
dir = "",
|
21 |
-
theme = false,
|
22 |
-
testMode = null,
|
23 |
-
defTheme = "claro",
|
24 |
-
vars={};
|
25 |
-
|
26 |
-
if(window.location.href.indexOf("?") > -1){
|
27 |
-
var str = window.location.href.substr(window.location.href.indexOf("?")+1).split(/#/);
|
28 |
-
var ary = str[0].split(/&/);
|
29 |
-
for(var i=0; i<ary.length; i++){
|
30 |
-
var split = ary[i].split("="),
|
31 |
-
key = split[0],
|
32 |
-
value = (split[1]||'').replace(/[^\w]/g, ""); // replace() to prevent XSS attack
|
33 |
-
switch(key){
|
34 |
-
case "locale":
|
35 |
-
// locale string | null
|
36 |
-
dojo.locale = dojo.config.locale = locale = value;
|
37 |
-
break;
|
38 |
-
case "dir":
|
39 |
-
// rtl | null
|
40 |
-
document.getElementsByTagName("html")[0].dir = value;
|
41 |
-
dir = value;
|
42 |
-
break;
|
43 |
-
case "theme":
|
44 |
-
// tundra | soria | nihilo | claro | null
|
45 |
-
theme = value;
|
46 |
-
break;
|
47 |
-
case "a11y":
|
48 |
-
if(value){ testMode = "dijit_a11y"; }
|
49 |
-
}
|
50 |
-
vars[key] = value;
|
51 |
-
}
|
52 |
-
}
|
53 |
-
d._getVar = function(k, def){
|
54 |
-
return vars[k] || def;
|
55 |
-
}
|
56 |
-
|
57 |
-
// If URL specifies a non-claro theme then pull in those theme CSS files and modify
|
58 |
-
// <body> to point to that new theme instead of claro.
|
59 |
-
//
|
60 |
-
// Also defer parsing and any dojo.addOnLoad() calls that the test file makes
|
61 |
-
// until the CSS has finished loading.
|
62 |
-
if(theme || testMode || dir){
|
63 |
-
|
64 |
-
if(theme){
|
65 |
-
var themeCss = d.moduleUrl("dijit.themes",theme+"/"+theme+".css");
|
66 |
-
var themeCssRtl = d.moduleUrl("dijit.themes",theme+"/"+theme+"_rtl.css");
|
67 |
-
|
68 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
69 |
-
// document.write('<link rel="stylesheet" type="text/css" href="'+themeCss+'"/>');
|
70 |
-
// FIXED:
|
71 |
-
|
72 |
-
document.write('<link rel="stylesheet" type="text/css" href="'+themeCssRtl+'"/>');
|
73 |
-
}
|
74 |
-
|
75 |
-
if(dojo.config.parseOnLoad){
|
76 |
-
dojo.config.parseOnLoad = false;
|
77 |
-
dojo.config._deferParsing = true;
|
78 |
-
|
79 |
-
// Capture any dojo.addOnLoad() calls the test makes and defer them until after
|
80 |
-
// the new CSS loads. (TODO: would be more straightforward to just make a
|
81 |
-
// testAddOnLoad() function and call that from the test files)
|
82 |
-
var originalOnLoad = dojo.addOnLoad,
|
83 |
-
loadFuncs = [];
|
84 |
-
dojo.addOnLoad = function(f){ loadFuncs.push(f); };
|
85 |
-
}
|
86 |
-
|
87 |
-
(originalOnLoad || dojo.addOnLoad)(function(){
|
88 |
-
// Reset <body> to point to the specified theme
|
89 |
-
var b = dojo.body();
|
90 |
-
if(theme){
|
91 |
-
dojo.removeClass(b, defTheme);
|
92 |
-
if(!d.hasClass(b, theme)){ d.addClass(b, theme); }
|
93 |
-
var n = d.byId("themeStyles");
|
94 |
-
if(n){ d.destroy(n); }
|
95 |
-
}
|
96 |
-
if(testMode){ d.addClass(b, testMode); }
|
97 |
-
|
98 |
-
// Claro has it's own reset css but for other themes using dojo/resources/dojo.css
|
99 |
-
if(theme){
|
100 |
-
dojo.query("style").forEach(function(node){
|
101 |
-
if(/claro\/document.css/.test(node.innerHTML)){
|
102 |
-
try{
|
103 |
-
node.innerHTML = node.innerHTML.replace("themes/claro/document.css",
|
104 |
-
"../dojo/resources/dojo.css");
|
105 |
-
}catch(e){
|
106 |
-
// fails on IE6-8 for some reason, works on IE9 and other browsers
|
107 |
-
}
|
108 |
-
}
|
109 |
-
});
|
110 |
-
}
|
111 |
-
if(dir == "rtl"){
|
112 |
-
// pretend all the labels are in an RTL language, because
|
113 |
-
// that affects how they lay out relative to inline form widgets
|
114 |
-
dojo.query("label").attr("dir", "rtl");
|
115 |
-
}
|
116 |
-
|
117 |
-
// Defer parsing and addOnLoad() execution until the specified CSS loads.
|
118 |
-
if(dojo.config._deferParsing){
|
119 |
-
setTimeout(function(){
|
120 |
-
dojo.addOnLoad = originalOnLoad;
|
121 |
-
dojo.parser.parse(b);
|
122 |
-
for(var i=0; i<loadFuncs.length; i++){
|
123 |
-
loadFuncs[i]();
|
124 |
-
}
|
125 |
-
}, 320);
|
126 |
-
}
|
127 |
-
|
128 |
-
});
|
129 |
-
}
|
130 |
-
|
131 |
-
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/132.js
DELETED
@@ -1,131 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
_testCommon.js - a simple module to be included in dijit test pages to allow
|
3 |
-
for easy switching between the many many points of the test-matrix.
|
4 |
-
|
5 |
-
in your test browser, provides a way to switch between available themes,
|
6 |
-
and optionally enable RTL (right to left) mode, and/or dijit_a11y (high-
|
7 |
-
constrast/image off emulation) ... probably not a genuine test for a11y.
|
8 |
-
|
9 |
-
usage: on any dijit test_* page, press ctrl-f9 to popup links.
|
10 |
-
|
11 |
-
there are currently (3 themes * 4 tests) * (10 variations of supported browsers)
|
12 |
-
not including testing individual locale-strings
|
13 |
-
|
14 |
-
you should NOT be using this in a production environment. include
|
15 |
-
your css and set your classes manually. for test purposes only ...
|
16 |
-
*/
|
17 |
-
|
18 |
-
(function(){
|
19 |
-
var d = dojo,
|
20 |
-
dir = "",
|
21 |
-
theme = false,
|
22 |
-
testMode = null,
|
23 |
-
defTheme = "claro",
|
24 |
-
vars={};
|
25 |
-
|
26 |
-
if(window.location.href.indexOf("?") > -1){
|
27 |
-
var str = window.location.href.substr(window.location.href.indexOf("?")+1).split(/#/);
|
28 |
-
var ary = str[0].split(/&/);
|
29 |
-
for(var i=0; i<ary.length; i++){
|
30 |
-
var split = ary[i].split("="),
|
31 |
-
key = split[0],
|
32 |
-
value = (split[1]||'').replace(/[^\w]/g, ""); // replace() to prevent XSS attack
|
33 |
-
switch(key){
|
34 |
-
case "locale":
|
35 |
-
// locale string | null
|
36 |
-
dojo.locale = dojo.config.locale = locale = value;
|
37 |
-
break;
|
38 |
-
case "dir":
|
39 |
-
// rtl | null
|
40 |
-
document.getElementsByTagName("html")[0].dir = value;
|
41 |
-
dir = value;
|
42 |
-
break;
|
43 |
-
case "theme":
|
44 |
-
// tundra | soria | nihilo | claro | null
|
45 |
-
theme = value;
|
46 |
-
break;
|
47 |
-
case "a11y":
|
48 |
-
if(value){ testMode = "dijit_a11y"; }
|
49 |
-
}
|
50 |
-
vars[key] = value;
|
51 |
-
}
|
52 |
-
}
|
53 |
-
d._getVar = function(k, def){
|
54 |
-
return vars[k] || def;
|
55 |
-
}
|
56 |
-
|
57 |
-
// If URL specifies a non-claro theme then pull in those theme CSS files and modify
|
58 |
-
// <body> to point to that new theme instead of claro.
|
59 |
-
//
|
60 |
-
// Also defer parsing and any dojo.addOnLoad() calls that the test file makes
|
61 |
-
// until the CSS has finished loading.
|
62 |
-
if(theme || testMode || dir){
|
63 |
-
|
64 |
-
if(theme){
|
65 |
-
var themeCss = d.moduleUrl("dijit.themes",theme+"/"+theme+".css");
|
66 |
-
var themeCssRtl = d.moduleUrl("dijit.themes",theme+"/"+theme+"_rtl.css");
|
67 |
-
document.write('<link rel="stylesheet" type="text/css" href="'+themeCss+'"/>');
|
68 |
-
|
69 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
70 |
-
// document.write('<link rel="stylesheet" type="text/css" href="'+themeCssRtl+'"/>');
|
71 |
-
// FIXED:
|
72 |
-
|
73 |
-
}
|
74 |
-
|
75 |
-
if(dojo.config.parseOnLoad){
|
76 |
-
dojo.config.parseOnLoad = false;
|
77 |
-
dojo.config._deferParsing = true;
|
78 |
-
|
79 |
-
// Capture any dojo.addOnLoad() calls the test makes and defer them until after
|
80 |
-
// the new CSS loads. (TODO: would be more straightforward to just make a
|
81 |
-
// testAddOnLoad() function and call that from the test files)
|
82 |
-
var originalOnLoad = dojo.addOnLoad,
|
83 |
-
loadFuncs = [];
|
84 |
-
dojo.addOnLoad = function(f){ loadFuncs.push(f); };
|
85 |
-
}
|
86 |
-
|
87 |
-
(originalOnLoad || dojo.addOnLoad)(function(){
|
88 |
-
// Reset <body> to point to the specified theme
|
89 |
-
var b = dojo.body();
|
90 |
-
if(theme){
|
91 |
-
dojo.removeClass(b, defTheme);
|
92 |
-
if(!d.hasClass(b, theme)){ d.addClass(b, theme); }
|
93 |
-
var n = d.byId("themeStyles");
|
94 |
-
if(n){ d.destroy(n); }
|
95 |
-
}
|
96 |
-
if(testMode){ d.addClass(b, testMode); }
|
97 |
-
|
98 |
-
// Claro has it's own reset css but for other themes using dojo/resources/dojo.css
|
99 |
-
if(theme){
|
100 |
-
dojo.query("style").forEach(function(node){
|
101 |
-
if(/claro\/document.css/.test(node.innerHTML)){
|
102 |
-
try{
|
103 |
-
node.innerHTML = node.innerHTML.replace("themes/claro/document.css",
|
104 |
-
"../dojo/resources/dojo.css");
|
105 |
-
}catch(e){
|
106 |
-
// fails on IE6-8 for some reason, works on IE9 and other browsers
|
107 |
-
}
|
108 |
-
}
|
109 |
-
});
|
110 |
-
}
|
111 |
-
if(dir == "rtl"){
|
112 |
-
// pretend all the labels are in an RTL language, because
|
113 |
-
// that affects how they lay out relative to inline form widgets
|
114 |
-
dojo.query("label").attr("dir", "rtl");
|
115 |
-
}
|
116 |
-
|
117 |
-
// Defer parsing and addOnLoad() execution until the specified CSS loads.
|
118 |
-
if(dojo.config._deferParsing){
|
119 |
-
setTimeout(function(){
|
120 |
-
dojo.addOnLoad = originalOnLoad;
|
121 |
-
dojo.parser.parse(b);
|
122 |
-
for(var i=0; i<loadFuncs.length; i++){
|
123 |
-
loadFuncs[i]();
|
124 |
-
}
|
125 |
-
}, 320);
|
126 |
-
}
|
127 |
-
|
128 |
-
});
|
129 |
-
}
|
130 |
-
|
131 |
-
})();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/133.js
DELETED
@@ -1,394 +0,0 @@
|
|
1 |
-
define("dojo/back", ["dojo"], function(dojo) {
|
2 |
-
dojo.getObject("back", true, dojo);
|
3 |
-
|
4 |
-
/*=====
|
5 |
-
dojo.back = {
|
6 |
-
// summary: Browser history management resources
|
7 |
-
}
|
8 |
-
=====*/
|
9 |
-
|
10 |
-
|
11 |
-
(function(){
|
12 |
-
var back = dojo.back,
|
13 |
-
|
14 |
-
// everyone deals with encoding the hash slightly differently
|
15 |
-
|
16 |
-
getHash= back.getHash= function(){
|
17 |
-
var h = window.location.hash;
|
18 |
-
if(h.charAt(0) == "#"){ h = h.substring(1); }
|
19 |
-
return dojo.isMozilla ? h : decodeURIComponent(h);
|
20 |
-
},
|
21 |
-
|
22 |
-
setHash= back.setHash= function(h){
|
23 |
-
if(!h){ h = ""; }
|
24 |
-
window.location.hash = encodeURIComponent(h);
|
25 |
-
historyCounter = history.length;
|
26 |
-
};
|
27 |
-
|
28 |
-
var initialHref = (typeof(window) !== "undefined") ? window.location.href : "";
|
29 |
-
var initialHash = (typeof(window) !== "undefined") ? getHash() : "";
|
30 |
-
var initialState = null;
|
31 |
-
|
32 |
-
var locationTimer = null;
|
33 |
-
var bookmarkAnchor = null;
|
34 |
-
var historyIframe = null;
|
35 |
-
var forwardStack = [];
|
36 |
-
var historyStack = [];
|
37 |
-
var moveForward = false;
|
38 |
-
var changingUrl = false;
|
39 |
-
var historyCounter;
|
40 |
-
|
41 |
-
function handleBackButton(){
|
42 |
-
//summary: private method. Do not call this directly.
|
43 |
-
|
44 |
-
//The "current" page is always at the top of the history stack.
|
45 |
-
var current = historyStack.pop();
|
46 |
-
if(!current){ return; }
|
47 |
-
var last = historyStack[historyStack.length-1];
|
48 |
-
if(!last && historyStack.length == 0){
|
49 |
-
last = initialState;
|
50 |
-
}
|
51 |
-
if(last){
|
52 |
-
if(last.kwArgs["back"]){
|
53 |
-
last.kwArgs["back"]();
|
54 |
-
}else if(last.kwArgs["backButton"]){
|
55 |
-
last.kwArgs["backButton"]();
|
56 |
-
}else if(last.kwArgs["handle"]){
|
57 |
-
last.kwArgs.handle("back");
|
58 |
-
}
|
59 |
-
}
|
60 |
-
forwardStack.push(current);
|
61 |
-
}
|
62 |
-
|
63 |
-
back.goBack = handleBackButton;
|
64 |
-
|
65 |
-
function handleForwardButton(){
|
66 |
-
//summary: private method. Do not call this directly.
|
67 |
-
var last = forwardStack.pop();
|
68 |
-
if(!last){ return; }
|
69 |
-
if(last.kwArgs["forward"]){
|
70 |
-
last.kwArgs.forward();
|
71 |
-
}else if(last.kwArgs["forwardButton"]){
|
72 |
-
last.kwArgs.forwardButton();
|
73 |
-
}else if(last.kwArgs["handle"]){
|
74 |
-
last.kwArgs.handle("forward");
|
75 |
-
}
|
76 |
-
historyStack.push(last);
|
77 |
-
}
|
78 |
-
|
79 |
-
back.goForward = handleForwardButton;
|
80 |
-
|
81 |
-
function createState(url, args, hash){
|
82 |
-
//summary: private method. Do not call this directly.
|
83 |
-
return {"url": url, "kwArgs": args, "urlHash": hash}; //Object
|
84 |
-
}
|
85 |
-
|
86 |
-
function getUrlQuery(url){
|
87 |
-
//summary: private method. Do not call this directly.
|
88 |
-
var segments = url.split("?");
|
89 |
-
if(segments.length < 2){
|
90 |
-
return null; //null
|
91 |
-
}
|
92 |
-
else{
|
93 |
-
return segments[1]; //String
|
94 |
-
}
|
95 |
-
}
|
96 |
-
|
97 |
-
function loadIframeHistory(){
|
98 |
-
//summary: private method. Do not call this directly.
|
99 |
-
var url = (dojo.config["dojoIframeHistoryUrl"] || dojo.moduleUrl("dojo", "resources/iframe_history.html")) + "?" + (new Date()).getTime();
|
100 |
-
moveForward = true;
|
101 |
-
if(historyIframe){
|
102 |
-
dojo.isWebKit ? historyIframe.location = url : window.frames[historyIframe.name].location = url;
|
103 |
-
}else{
|
104 |
-
//console.warn("dojo.back: Not initialised. You need to call dojo.back.init() from a <script> block that lives inside the <body> tag.");
|
105 |
-
}
|
106 |
-
return url; //String
|
107 |
-
}
|
108 |
-
|
109 |
-
function checkLocation(){
|
110 |
-
if(!changingUrl){
|
111 |
-
var hsl = historyStack.length;
|
112 |
-
|
113 |
-
var hash = getHash();
|
114 |
-
|
115 |
-
if((hash === initialHash||window.location.href == initialHref)&&(hsl == 1)){
|
116 |
-
// FIXME: could this ever be a forward button?
|
117 |
-
// we can't clear it because we still need to check for forwards. Ugg.
|
118 |
-
// clearInterval(this.locationTimer);
|
119 |
-
handleBackButton();
|
120 |
-
return;
|
121 |
-
}
|
122 |
-
|
123 |
-
// first check to see if we could have gone forward. We always halt on
|
124 |
-
// a no-hash item.
|
125 |
-
if(forwardStack.length > 0){
|
126 |
-
if(forwardStack[forwardStack.length-1].urlHash === hash){
|
127 |
-
handleForwardButton();
|
128 |
-
return;
|
129 |
-
}
|
130 |
-
}
|
131 |
-
|
132 |
-
// ok, that didn't work, try someplace back in the history stack
|
133 |
-
if((hsl >= 2)&&(historyStack[hsl-2])){
|
134 |
-
if(historyStack[hsl-2].urlHash === hash){
|
135 |
-
handleBackButton();
|
136 |
-
return;
|
137 |
-
}
|
138 |
-
}
|
139 |
-
}
|
140 |
-
};
|
141 |
-
|
142 |
-
back.init = function(){
|
143 |
-
//summary: Initializes the undo stack. This must be called from a <script>
|
144 |
-
// block that lives inside the <body> tag to prevent bugs on IE.
|
145 |
-
// description:
|
146 |
-
// Only call this method before the page's DOM is finished loading. Otherwise
|
147 |
-
// it will not work. Be careful with xdomain loading or djConfig.debugAtAllCosts scenarios,
|
148 |
-
// in order for this method to work, dojo.back will need to be part of a build layer.
|
149 |
-
if(dojo.byId("dj_history")){ return; } // prevent reinit
|
150 |
-
var src = dojo.config["dojoIframeHistoryUrl"] || dojo.moduleUrl("dojo", "resources/iframe_history.html");
|
151 |
-
if (dojo._postLoad) {
|
152 |
-
console.error("dojo.back.init() must be called before the DOM has loaded. "
|
153 |
-
+ "If using xdomain loading or djConfig.debugAtAllCosts, include dojo.back "
|
154 |
-
+ "in a build layer.");
|
155 |
-
} else {
|
156 |
-
|
157 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
158 |
-
// 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>');
|
159 |
-
// FIXED:
|
160 |
-
|
161 |
-
}
|
162 |
-
};
|
163 |
-
|
164 |
-
back.setInitialState = function(/*Object*/args){
|
165 |
-
//summary:
|
166 |
-
// Sets the state object and back callback for the very first page
|
167 |
-
// that is loaded.
|
168 |
-
//description:
|
169 |
-
// It is recommended that you call this method as part of an event
|
170 |
-
// listener that is registered via dojo.addOnLoad().
|
171 |
-
//args: Object
|
172 |
-
// See the addToHistory() function for the list of valid args properties.
|
173 |
-
initialState = createState(initialHref, args, initialHash);
|
174 |
-
};
|
175 |
-
|
176 |
-
//FIXME: Make these doc comments not be awful. At least they're not wrong.
|
177 |
-
//FIXME: Would like to support arbitrary back/forward jumps. Have to rework iframeLoaded among other things.
|
178 |
-
//FIXME: is there a slight race condition in moz using change URL with the timer check and when
|
179 |
-
// the hash gets set? I think I have seen a back/forward call in quick succession, but not consistent.
|
180 |
-
|
181 |
-
|
182 |
-
/*=====
|
183 |
-
dojo.__backArgs = function(kwArgs){
|
184 |
-
// back: Function?
|
185 |
-
// A function to be called when this state is reached via the user
|
186 |
-
// clicking the back button.
|
187 |
-
// forward: Function?
|
188 |
-
// Upon return to this state from the "back, forward" combination
|
189 |
-
// of navigation steps, this function will be called. Somewhat
|
190 |
-
// analgous to the semantic of an "onRedo" event handler.
|
191 |
-
// changeUrl: Boolean?|String?
|
192 |
-
// Boolean indicating whether or not to create a unique hash for
|
193 |
-
// this state. If a string is passed instead, it is used as the
|
194 |
-
// hash.
|
195 |
-
}
|
196 |
-
=====*/
|
197 |
-
|
198 |
-
back.addToHistory = function(/*dojo.__backArgs*/ args){
|
199 |
-
// summary:
|
200 |
-
// adds a state object (args) to the history list.
|
201 |
-
// description:
|
202 |
-
// To support getting back button notifications, the object
|
203 |
-
// argument should implement a function called either "back",
|
204 |
-
// "backButton", or "handle". The string "back" will be passed as
|
205 |
-
// the first and only argument to this callback.
|
206 |
-
//
|
207 |
-
// To support getting forward button notifications, the object
|
208 |
-
// argument should implement a function called either "forward",
|
209 |
-
// "forwardButton", or "handle". The string "forward" will be
|
210 |
-
// passed as the first and only argument to this callback.
|
211 |
-
//
|
212 |
-
// If you want the browser location string to change, define "changeUrl" on the object. If the
|
213 |
-
// value of "changeUrl" is true, then a unique number will be appended to the URL as a fragment
|
214 |
-
// identifier (http://some.domain.com/path#uniquenumber). If it is any other value that does
|
215 |
-
// not evaluate to false, that value will be used as the fragment identifier. For example,
|
216 |
-
// if changeUrl: 'page1', then the URL will look like: http://some.domain.com/path#page1
|
217 |
-
//
|
218 |
-
// There are problems with using dojo.back with semantically-named fragment identifiers
|
219 |
-
// ("hash values" on an URL). In most browsers it will be hard for dojo.back to know
|
220 |
-
// distinguish a back from a forward event in those cases. For back/forward support to
|
221 |
-
// work best, the fragment ID should always be a unique value (something using new Date().getTime()
|
222 |
-
// for example). If you want to detect hash changes using semantic fragment IDs, then
|
223 |
-
// consider using dojo.hash instead (in Dojo 1.4+).
|
224 |
-
//
|
225 |
-
// example:
|
226 |
-
// | dojo.back.addToHistory({
|
227 |
-
// | back: function(){ console.log('back pressed'); },
|
228 |
-
// | forward: function(){ console.log('forward pressed'); },
|
229 |
-
// | changeUrl: true
|
230 |
-
// | });
|
231 |
-
|
232 |
-
// BROWSER NOTES:
|
233 |
-
// Safari 1.2:
|
234 |
-
// back button "works" fine, however it's not possible to actually
|
235 |
-
// DETECT that you've moved backwards by inspecting window.location.
|
236 |
-
// Unless there is some other means of locating.
|
237 |
-
// FIXME: perhaps we can poll on history.length?
|
238 |
-
// Safari 2.0.3+ (and probably 1.3.2+):
|
239 |
-
// works fine, except when changeUrl is used. When changeUrl is used,
|
240 |
-
// Safari jumps all the way back to whatever page was shown before
|
241 |
-
// the page that uses dojo.undo.browser support.
|
242 |
-
// IE 5.5 SP2:
|
243 |
-
// back button behavior is macro. It does not move back to the
|
244 |
-
// previous hash value, but to the last full page load. This suggests
|
245 |
-
// that the iframe is the correct way to capture the back button in
|
246 |
-
// these cases.
|
247 |
-
// Don't test this page using local disk for MSIE. MSIE will not create
|
248 |
-
// a history list for iframe_history.html if served from a file: URL.
|
249 |
-
// The XML served back from the XHR tests will also not be properly
|
250 |
-
// created if served from local disk. Serve the test pages from a web
|
251 |
-
// server to test in that browser.
|
252 |
-
// IE 6.0:
|
253 |
-
// same behavior as IE 5.5 SP2
|
254 |
-
// Firefox 1.0+:
|
255 |
-
// the back button will return us to the previous hash on the same
|
256 |
-
// page, thereby not requiring an iframe hack, although we do then
|
257 |
-
// need to run a timer to detect inter-page movement.
|
258 |
-
|
259 |
-
//If addToHistory is called, then that means we prune the
|
260 |
-
//forward stack -- the user went back, then wanted to
|
261 |
-
//start a new forward path.
|
262 |
-
forwardStack = [];
|
263 |
-
|
264 |
-
var hash = null;
|
265 |
-
var url = null;
|
266 |
-
if(!historyIframe){
|
267 |
-
if(dojo.config["useXDomain"] && !dojo.config["dojoIframeHistoryUrl"]){
|
268 |
-
console.warn("dojo.back: When using cross-domain Dojo builds,"
|
269 |
-
+ " please save iframe_history.html to your domain and set djConfig.dojoIframeHistoryUrl"
|
270 |
-
+ " to the path on your domain to iframe_history.html");
|
271 |
-
}
|
272 |
-
historyIframe = window.frames["dj_history"];
|
273 |
-
}
|
274 |
-
if(!bookmarkAnchor){
|
275 |
-
bookmarkAnchor = dojo.create("a", {style: {display: "none"}}, dojo.body());
|
276 |
-
}
|
277 |
-
if(args["changeUrl"]){
|
278 |
-
hash = ""+ ((args["changeUrl"]!==true) ? args["changeUrl"] : (new Date()).getTime());
|
279 |
-
|
280 |
-
//If the current hash matches the new one, just replace the history object with
|
281 |
-
//this new one. It doesn't make sense to track different state objects for the same
|
282 |
-
//logical URL. This matches the browser behavior of only putting in one history
|
283 |
-
//item no matter how many times you click on the same #hash link, at least in Firefox
|
284 |
-
//and Safari, and there is no reliable way in those browsers to know if a #hash link
|
285 |
-
//has been clicked on multiple times. So making this the standard behavior in all browsers
|
286 |
-
//so that dojo.back's behavior is the same in all browsers.
|
287 |
-
if(historyStack.length == 0 && initialState.urlHash == hash){
|
288 |
-
initialState = createState(url, args, hash);
|
289 |
-
return;
|
290 |
-
}else if(historyStack.length > 0 && historyStack[historyStack.length - 1].urlHash == hash){
|
291 |
-
historyStack[historyStack.length - 1] = createState(url, args, hash);
|
292 |
-
return;
|
293 |
-
}
|
294 |
-
|
295 |
-
changingUrl = true;
|
296 |
-
setTimeout(function() {
|
297 |
-
setHash(hash);
|
298 |
-
changingUrl = false;
|
299 |
-
}, 1);
|
300 |
-
bookmarkAnchor.href = hash;
|
301 |
-
|
302 |
-
if(dojo.isIE){
|
303 |
-
url = loadIframeHistory();
|
304 |
-
|
305 |
-
var oldCB = args["back"]||args["backButton"]||args["handle"];
|
306 |
-
|
307 |
-
//The function takes handleName as a parameter, in case the
|
308 |
-
//callback we are overriding was "handle". In that case,
|
309 |
-
//we will need to pass the handle name to handle.
|
310 |
-
var tcb = function(handleName){
|
311 |
-
if(getHash() != ""){
|
312 |
-
setTimeout(function() { setHash(hash); }, 1);
|
313 |
-
}
|
314 |
-
//Use apply to set "this" to args, and to try to avoid memory leaks.
|
315 |
-
oldCB.apply(this, [handleName]);
|
316 |
-
};
|
317 |
-
|
318 |
-
//Set interceptor function in the right place.
|
319 |
-
if(args["back"]){
|
320 |
-
args.back = tcb;
|
321 |
-
}else if(args["backButton"]){
|
322 |
-
args.backButton = tcb;
|
323 |
-
}else if(args["handle"]){
|
324 |
-
args.handle = tcb;
|
325 |
-
}
|
326 |
-
|
327 |
-
var oldFW = args["forward"]||args["forwardButton"]||args["handle"];
|
328 |
-
|
329 |
-
//The function takes handleName as a parameter, in case the
|
330 |
-
//callback we are overriding was "handle". In that case,
|
331 |
-
//we will need to pass the handle name to handle.
|
332 |
-
var tfw = function(handleName){
|
333 |
-
if(getHash() != ""){
|
334 |
-
setHash(hash);
|
335 |
-
}
|
336 |
-
if(oldFW){ // we might not actually have one
|
337 |
-
//Use apply to set "this" to args, and to try to avoid memory leaks.
|
338 |
-
oldFW.apply(this, [handleName]);
|
339 |
-
}
|
340 |
-
};
|
341 |
-
|
342 |
-
//Set interceptor function in the right place.
|
343 |
-
if(args["forward"]){
|
344 |
-
args.forward = tfw;
|
345 |
-
}else if(args["forwardButton"]){
|
346 |
-
args.forwardButton = tfw;
|
347 |
-
}else if(args["handle"]){
|
348 |
-
args.handle = tfw;
|
349 |
-
}
|
350 |
-
|
351 |
-
}else if(!dojo.isIE){
|
352 |
-
// start the timer
|
353 |
-
if(!locationTimer){
|
354 |
-
locationTimer = setInterval(checkLocation, 200);
|
355 |
-
}
|
356 |
-
|
357 |
-
}
|
358 |
-
}else{
|
359 |
-
url = loadIframeHistory();
|
360 |
-
}
|
361 |
-
|
362 |
-
historyStack.push(createState(url, args, hash));
|
363 |
-
};
|
364 |
-
|
365 |
-
back._iframeLoaded = function(evt, ifrLoc){
|
366 |
-
//summary:
|
367 |
-
// private method. Do not call this directly.
|
368 |
-
var query = getUrlQuery(ifrLoc.href);
|
369 |
-
if(query == null){
|
370 |
-
// alert("iframeLoaded");
|
371 |
-
// we hit the end of the history, so we should go back
|
372 |
-
if(historyStack.length == 1){
|
373 |
-
handleBackButton();
|
374 |
-
}
|
375 |
-
return;
|
376 |
-
}
|
377 |
-
if(moveForward){
|
378 |
-
// we were expecting it, so it's not either a forward or backward movement
|
379 |
-
moveForward = false;
|
380 |
-
return;
|
381 |
-
}
|
382 |
-
|
383 |
-
//Check the back stack first, since it is more likely.
|
384 |
-
//Note that only one step back or forward is supported.
|
385 |
-
if(historyStack.length >= 2 && query == getUrlQuery(historyStack[historyStack.length-2].url)){
|
386 |
-
handleBackButton();
|
387 |
-
}else if(forwardStack.length > 0 && query == getUrlQuery(forwardStack[forwardStack.length-1].url)){
|
388 |
-
handleForwardButton();
|
389 |
-
}
|
390 |
-
};
|
391 |
-
})();
|
392 |
-
|
393 |
-
return dojo.back;
|
394 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/134.js
DELETED
@@ -1,42 +0,0 @@
|
|
1 |
-
const baseURL = 'http://localhost:9000/api/users/'
|
2 |
-
|
3 |
-
|
4 |
-
export const getUsers = () => {
|
5 |
-
|
6 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
7 |
-
// return fetch(baseURL)
|
8 |
-
// FIXED:
|
9 |
-
|
10 |
-
.then(res => res.json());
|
11 |
-
};
|
12 |
-
|
13 |
-
export const getUser = (id) => {
|
14 |
-
return fetch(baseURL + id)
|
15 |
-
.then(res => res.json())
|
16 |
-
};
|
17 |
-
|
18 |
-
export const postUser = (payload) => {
|
19 |
-
return fetch(baseURL, {
|
20 |
-
method: 'POST',
|
21 |
-
body: JSON.stringify(payload),
|
22 |
-
headers: {'Content-Type': 'application/json'}
|
23 |
-
})
|
24 |
-
.then(res => res.json())
|
25 |
-
};
|
26 |
-
|
27 |
-
export const putUser = (id , payload) => {
|
28 |
-
return fetch(baseURL + id, {
|
29 |
-
method: 'PUT',
|
30 |
-
body:JSON.stringify(payload),
|
31 |
-
headers : {'Content-Type': 'application/json'}
|
32 |
-
})
|
33 |
-
.then(res => res.json())
|
34 |
-
};
|
35 |
-
|
36 |
-
export const deleteUser = (id) => {
|
37 |
-
return fetch(baseURL + id, {
|
38 |
-
method: 'DELETE'
|
39 |
-
})
|
40 |
-
};
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/135.js
DELETED
@@ -1,38 +0,0 @@
|
|
1 |
-
const baseURL = 'http://localhost:9000/api/users/'
|
2 |
-
|
3 |
-
|
4 |
-
export const getUsers = () => {
|
5 |
-
return fetch(baseURL)
|
6 |
-
.then(res => res.json());
|
7 |
-
};
|
8 |
-
|
9 |
-
export const getUser = (id) => {
|
10 |
-
return fetch(baseURL + id)
|
11 |
-
.then(res => res.json())
|
12 |
-
};
|
13 |
-
|
14 |
-
export const postUser = (payload) => {
|
15 |
-
|
16 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
17 |
-
// return fetch(baseURL, { method: 'POST', body: JSON.stringify(payload), headers: {'Content-Type': 'application/json'} })
|
18 |
-
// FIXED:
|
19 |
-
|
20 |
-
.then(res => res.json())
|
21 |
-
};
|
22 |
-
|
23 |
-
export const putUser = (id , payload) => {
|
24 |
-
return fetch(baseURL + id, {
|
25 |
-
method: 'PUT',
|
26 |
-
body:JSON.stringify(payload),
|
27 |
-
headers : {'Content-Type': 'application/json'}
|
28 |
-
})
|
29 |
-
.then(res => res.json())
|
30 |
-
};
|
31 |
-
|
32 |
-
export const deleteUser = (id) => {
|
33 |
-
return fetch(baseURL + id, {
|
34 |
-
method: 'DELETE'
|
35 |
-
})
|
36 |
-
};
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/136.js
DELETED
@@ -1,12 +0,0 @@
|
|
1 |
-
const baseURL = 'http://localhost:9000/api/words/'
|
2 |
-
|
3 |
-
export const getWords = () => {
|
4 |
-
|
5 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
6 |
-
// return fetch(baseURL)
|
7 |
-
// FIXED:
|
8 |
-
|
9 |
-
.then(res => res.json())
|
10 |
-
}
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/137.js
DELETED
@@ -1,311 +0,0 @@
|
|
1 |
-
const http = require('http');
|
2 |
-
const https = require('https');
|
3 |
-
const express = require('express');
|
4 |
-
const path = require('path');
|
5 |
-
const cookieParser = require('cookie-parser');
|
6 |
-
const bodyParser = require('body-parser');
|
7 |
-
const session = require('express-session');
|
8 |
-
const util = require('util');
|
9 |
-
const figlet = require('figlet');
|
10 |
-
const CronJob = require('cron').CronJob;
|
11 |
-
|
12 |
-
const confMgmt = require('../api/conf-mgmt');
|
13 |
-
const confConsts = require('../common/conf-constants');
|
14 |
-
const restUrls = require('../common/rest-urls');
|
15 |
-
const storageUtils = require('../api/storage-utils');
|
16 |
-
const utils = require('../api/utils');
|
17 |
-
const logger = require('../api/logger');
|
18 |
-
const security = require('../api/security');
|
19 |
-
const fsx = require('../api/fsx');
|
20 |
-
const schemas = require('../common/schemas');
|
21 |
-
const version = require('../../package.json').version;
|
22 |
-
|
23 |
-
const notFoundInterceptor = require('../interceptors/404-interceptor');
|
24 |
-
const errorHandlerInterceptor = require('../interceptors/error-handler-interceptor');
|
25 |
-
|
26 |
-
const staticSite = require('../routes/root/root-route');
|
27 |
-
const storageRoute = require('../routes/storage/storage-route');
|
28 |
-
const general = require('../routes/general/general-route');
|
29 |
-
const usersRoute = require('../routes/users/users-route');
|
30 |
-
const permissionsRoute = require('../routes/permissions/permissions-route');
|
31 |
-
const settingsRoute = require('../routes/settings/settings-route');
|
32 |
-
const webhooksRoute = require('../routes/webhooks-route');
|
33 |
-
const expressionsRoute = require('../routes/expressions/expressions-route');
|
34 |
-
const reservedRoute = require('../routes/reserved/reserved-route');
|
35 |
-
|
36 |
-
let nexlApp, httpServer, httpsServer;
|
37 |
-
|
38 |
-
function printWelcomeMessage() {
|
39 |
-
return new Promise(
|
40 |
-
(resolve, reject) => {
|
41 |
-
figlet.text('nexl ' + version, {font: 'Doom'}, function (err, data) {
|
42 |
-
if (err) {
|
43 |
-
reject(err);
|
44 |
-
return;
|
45 |
-
}
|
46 |
-
|
47 |
-
console.log(data);
|
48 |
-
resolve();
|
49 |
-
});
|
50 |
-
|
51 |
-
});
|
52 |
-
}
|
53 |
-
|
54 |
-
|
55 |
-
function create(interceptors) {
|
56 |
-
nexlApp = express();
|
57 |
-
|
58 |
-
( interceptors || [] ).forEach(item => {
|
59 |
-
nexlApp.use(item);
|
60 |
-
});
|
61 |
-
|
62 |
-
// static resources, root page, nexl rest, nexl expressions
|
63 |
-
nexlApp.use(express.static(path.join(__dirname, '../../site')));
|
64 |
-
|
65 |
-
// index html
|
66 |
-
nexlApp.use('/', staticSite);
|
67 |
-
|
68 |
-
// general interceptors
|
69 |
-
|
70 |
-
// BUG: CWE-522: Insufficiently Protected Credentials
|
71 |
-
// nexlApp.use(session({ secret: utils.generateRandomBytes(64), resave: false, saveUninitialized: false }));
|
72 |
-
// FIXED:
|
73 |
-
|
74 |
-
|
75 |
-
nexlApp.use(bodyParser.json());
|
76 |
-
nexlApp.use(bodyParser.urlencoded({extended: false}));
|
77 |
-
nexlApp.use(cookieParser());
|
78 |
-
|
79 |
-
// auth interceptor
|
80 |
-
nexlApp.use(security.authInterceptor);
|
81 |
-
|
82 |
-
// logger to log REST requests
|
83 |
-
nexlApp.use(logger.loggerInterceptor);
|
84 |
-
|
85 |
-
// REST routes
|
86 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.STORAGE.PREFIX}/`, storageRoute);
|
87 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.USERS.PREFIX}/`, usersRoute);
|
88 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.PERMISSIONS.PREFIX}/`, permissionsRoute);
|
89 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.SETTINGS.PREFIX}/`, settingsRoute);
|
90 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.WEBHOOKS.PREFIX}/`, webhooksRoute);
|
91 |
-
nexlApp.use(`/${restUrls.ROOT}/${restUrls.GENERAL.PREFIX}/`, general);
|
92 |
-
nexlApp.use(`/${restUrls.ROOT}/`, reservedRoute);
|
93 |
-
nexlApp.use('/', expressionsRoute);
|
94 |
-
|
95 |
-
// catch 404 and forward to error handler
|
96 |
-
nexlApp.use(notFoundInterceptor);
|
97 |
-
|
98 |
-
// error handler
|
99 |
-
nexlApp.use(errorHandlerInterceptor);
|
100 |
-
|
101 |
-
return printWelcomeMessage()
|
102 |
-
.then(confMgmt.initNexlHomeDir)
|
103 |
-
.then(logger.configureLoggers)
|
104 |
-
.then(confMgmt.preloadConfs);
|
105 |
-
}
|
106 |
-
|
107 |
-
function httpError(error) {
|
108 |
-
if (error.syscall !== 'listen') {
|
109 |
-
logger.log.error('Cannot start HTTP listener. Reason : [%s]', utils.formatErr(error));
|
110 |
-
process.exit(1);
|
111 |
-
}
|
112 |
-
|
113 |
-
const settings = confMgmt.getNexlSettingsCached();
|
114 |
-
|
115 |
-
// handling specific listen errors with friendly messages
|
116 |
-
switch (error.code) {
|
117 |
-
case 'EACCES':
|
118 |
-
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));
|
119 |
-
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);
|
120 |
-
process.exit(1);
|
121 |
-
break;
|
122 |
-
case 'EADDRINUSE':
|
123 |
-
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));
|
124 |
-
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);
|
125 |
-
process.exit(1);
|
126 |
-
break;
|
127 |
-
default:
|
128 |
-
logger.log.importantMessage('info', 'HTTP server error. Reason : [%s]', utils.formatErr(error));
|
129 |
-
process.exit(1);
|
130 |
-
}
|
131 |
-
}
|
132 |
-
|
133 |
-
function startHTTPServer() {
|
134 |
-
const settings = confMgmt.getNexlSettingsCached();
|
135 |
-
if (!schemas.hasHttpConnector(settings)) {
|
136 |
-
logger.log.debug(`HTTP binding and/or port is not provided. Not starting HTTP listener`);
|
137 |
-
return Promise.resolve();
|
138 |
-
}
|
139 |
-
|
140 |
-
return new Promise((resolve, reject) => {
|
141 |
-
// creating http server
|
142 |
-
try {
|
143 |
-
httpServer = http.createServer(nexlApp);
|
144 |
-
} catch (err) {
|
145 |
-
logger.log.error('Failed to start HTTP server. Reason : [%s]', utils.formatErr(e));
|
146 |
-
reject(err);
|
147 |
-
return;
|
148 |
-
}
|
149 |
-
|
150 |
-
const settings = confMgmt.getNexlSettingsCached();
|
151 |
-
httpServer.setTimeout(reCalcHttpTimeout(settings[confConsts.SETTINGS.HTTP_TIMEOUT]));
|
152 |
-
|
153 |
-
// error event handler
|
154 |
-
httpServer.on('error', (error) => {
|
155 |
-
httpError(error);
|
156 |
-
});
|
157 |
-
|
158 |
-
// listening handler
|
159 |
-
httpServer.on('listening', () => {
|
160 |
-
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` : '';
|
161 |
-
logger.log.importantMessage('info', 'nexl HTTP server is up and listening on [%s:%s]%s', httpServer.address().address, httpServer.address().port, localBindingMsg);
|
162 |
-
resolve();
|
163 |
-
});
|
164 |
-
|
165 |
-
// starting http server
|
166 |
-
httpServer.listen(settings[confConsts.SETTINGS.HTTP_PORT], settings[confConsts.SETTINGS.HTTP_BINDING]);
|
167 |
-
});
|
168 |
-
}
|
169 |
-
|
170 |
-
function assembleSSLCerts() {
|
171 |
-
const settings = confMgmt.getNexlSettingsCached();
|
172 |
-
const sslCert = settings[confConsts.SETTINGS.SSL_CERT_LOCATION];
|
173 |
-
const sslKey = settings[confConsts.SETTINGS.SSL_KEY_LOCATION];
|
174 |
-
|
175 |
-
return fsx.exists(sslCert).then((isExists) => {
|
176 |
-
if (!isExists) {
|
177 |
-
return Promise.reject(util.format('The [%s] SSL cert file doesn\'t exist', sslCert));
|
178 |
-
}
|
179 |
-
|
180 |
-
return fsx.exists(sslKey).then((isExists) => {
|
181 |
-
if (!isExists) {
|
182 |
-
return Promise.reject(util.format('The [%s] SSL key file doesn\'t exist', sslKey));
|
183 |
-
}
|
184 |
-
|
185 |
-
return fsx.readFile(sslCert).then((certFile) => {
|
186 |
-
return fsx.readFile(sslKey).then((keyFile) => Promise.resolve({
|
187 |
-
key: keyFile,
|
188 |
-
cert: certFile
|
189 |
-
}))
|
190 |
-
});
|
191 |
-
});
|
192 |
-
});
|
193 |
-
}
|
194 |
-
|
195 |
-
function httpsError() {
|
196 |
-
if (error.syscall !== 'listen') {
|
197 |
-
logger.log.error('Cannot start HTTPS listener. Reason : [%s]', utils.formatErr(error));
|
198 |
-
process.exit(1);
|
199 |
-
}
|
200 |
-
|
201 |
-
// handling specific listen errors with friendly messages
|
202 |
-
switch (error.code) {
|
203 |
-
case 'EACCES':
|
204 |
-
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));
|
205 |
-
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);
|
206 |
-
process.exit(1);
|
207 |
-
break;
|
208 |
-
case 'EADDRINUSE':
|
209 |
-
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));
|
210 |
-
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);
|
211 |
-
process.exit(1);
|
212 |
-
break;
|
213 |
-
default:
|
214 |
-
logger.log.importantMessage('info', 'HTTPS server error. Reason : [%s]', utils.formatErr(error));
|
215 |
-
process.exit(1);
|
216 |
-
}
|
217 |
-
}
|
218 |
-
|
219 |
-
function startHTTPSServerInner(sslCredentials) {
|
220 |
-
return new Promise((resolve, reject) => {
|
221 |
-
// creating http server
|
222 |
-
try {
|
223 |
-
httpsServer = https.createServer(sslCredentials, nexlApp);
|
224 |
-
} catch (err) {
|
225 |
-
logger.log.error('Failed to start HTTPS server. Reason : [%s]', utils.formatErr(err));
|
226 |
-
reject(err);
|
227 |
-
return;
|
228 |
-
}
|
229 |
-
|
230 |
-
const settings = confMgmt.getNexlSettingsCached();
|
231 |
-
httpsServer.setTimeout(reCalcHttpTimeout(settings[confConsts.SETTINGS.HTTP_TIMEOUT]));
|
232 |
-
|
233 |
-
// error event handler
|
234 |
-
httpsServer.on('error', (error) => {
|
235 |
-
httpsError(error);
|
236 |
-
});
|
237 |
-
|
238 |
-
// listening handler
|
239 |
-
httpsServer.on('listening', () => {
|
240 |
-
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` : '';
|
241 |
-
logger.log.importantMessage('info', 'nexl HTTPS server is up and listening on [%s:%s]%s', httpServer.address().address, httpServer.address().port, localBindingMsg);
|
242 |
-
resolve();
|
243 |
-
});
|
244 |
-
|
245 |
-
// starting http server
|
246 |
-
httpsServer.listen(settings[confConsts.SETTINGS.HTTPS_PORT], settings[confConsts.SETTINGS.HTTPS_BINDING]);
|
247 |
-
});
|
248 |
-
}
|
249 |
-
|
250 |
-
function startHTTPSServer() {
|
251 |
-
const settings = confMgmt.getNexlSettingsCached();
|
252 |
-
if (!schemas.hasHttpsConnector(settings)) {
|
253 |
-
logger.log.debug(`HTTPS binding|port|cert|key is not provided. Not starting HTTPS listener`);
|
254 |
-
return Promise.resolve();
|
255 |
-
}
|
256 |
-
|
257 |
-
return assembleSSLCerts().then(startHTTPSServerInner);
|
258 |
-
}
|
259 |
-
|
260 |
-
function start() {
|
261 |
-
return Promise.resolve()
|
262 |
-
.then(confMgmt.createStorageDirIfNeeded)
|
263 |
-
.then(storageUtils.cacheStorageFiles)
|
264 |
-
.then(startHTTPServer)
|
265 |
-
.then(startHTTPSServer)
|
266 |
-
.then(storageUtils.scheduleAutoamticBackup)
|
267 |
-
.then(_ => {
|
268 |
-
logger.log.info(`nexl home dir is [${confMgmt.getNexlHomeDir()}]`);
|
269 |
-
logger.log.info(`nexl app data dir is [${confMgmt.getNexlAppDataDir()}]`);
|
270 |
-
logger.log.info(`nexl logs dir is [${confMgmt.getNexlSettingsCached()[confConsts.SETTINGS.LOG_FILE_LOCATION]}]`);
|
271 |
-
logger.log.info(`nexl storage dir is [${confMgmt.getNexlStorageDir()}]`);
|
272 |
-
return Promise.resolve();
|
273 |
-
})
|
274 |
-
.catch(
|
275 |
-
err => {
|
276 |
-
console.log(err);
|
277 |
-
process.exit(1);
|
278 |
-
});
|
279 |
-
|
280 |
-
}
|
281 |
-
|
282 |
-
function stop() {
|
283 |
-
if (httpServer !== undefined) {
|
284 |
-
httpServer.close();
|
285 |
-
}
|
286 |
-
|
287 |
-
if (httpsServer !== undefined) {
|
288 |
-
httpsServer.close();
|
289 |
-
}
|
290 |
-
}
|
291 |
-
|
292 |
-
function reCalcHttpTimeout(timeout) {
|
293 |
-
return timeout * 1000;
|
294 |
-
}
|
295 |
-
|
296 |
-
function setHttpTimeout(timeout) {
|
297 |
-
if (httpServer !== undefined) {
|
298 |
-
httpServer.setTimeout(reCalcHttpTimeout(timeout));
|
299 |
-
}
|
300 |
-
|
301 |
-
if (httpsServer !== undefined) {
|
302 |
-
httpsServer.setTimeout(reCalcHttpTimeout(timeout));
|
303 |
-
}
|
304 |
-
}
|
305 |
-
|
306 |
-
// --------------------------------------------------------------------------------
|
307 |
-
module.exports.create = create;
|
308 |
-
module.exports.start = start;
|
309 |
-
module.exports.stop = stop;
|
310 |
-
module.exports.setHttpTimeout = setHttpTimeout;
|
311 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/138.js
DELETED
@@ -1,531 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const path = require('path');
|
3 |
-
const j79 = require('j79-utils');
|
4 |
-
const nexlEngine = require('nexl-engine');
|
5 |
-
|
6 |
-
const storageUtils = require('../../api/storage-utils');
|
7 |
-
const security = require('../../api/security');
|
8 |
-
const utils = require('../../api/utils');
|
9 |
-
const logger = require('../../api/logger');
|
10 |
-
const restUtls = require('../../common/rest-urls');
|
11 |
-
const di = require('../../common/data-interchange-constants');
|
12 |
-
const confMgmt = require('../../api/conf-mgmt');
|
13 |
-
const confConsts = require('../../common/conf-constants');
|
14 |
-
const diConsts = require('../../common/data-interchange-constants');
|
15 |
-
|
16 |
-
const router = express.Router();
|
17 |
-
|
18 |
-
//////////////////////////////////////////////////////////////////////////////
|
19 |
-
// [/nexl/storage/set-var]
|
20 |
-
//////////////////////////////////////////////////////////////////////////////
|
21 |
-
router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) {
|
22 |
-
// checking for permissions
|
23 |
-
const username = security.getLoggedInUsername(req);
|
24 |
-
if (!security.hasWritePermission(username)) {
|
25 |
-
logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username);
|
26 |
-
security.sendError(res, 'No write permissions');
|
27 |
-
return;
|
28 |
-
}
|
29 |
-
|
30 |
-
// resolving params
|
31 |
-
const relativePath = req.body['relativePath'];
|
32 |
-
const varName = req.body['varName'];
|
33 |
-
const newValue = req.body['newValue'];
|
34 |
-
|
35 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`);
|
36 |
-
|
37 |
-
// validating relativePath
|
38 |
-
if (!relativePath) {
|
39 |
-
logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
40 |
-
security.sendError(res, 'The [relativePath] is not provided');
|
41 |
-
return;
|
42 |
-
}
|
43 |
-
|
44 |
-
// validating varName
|
45 |
-
if (!varName) {
|
46 |
-
logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
47 |
-
security.sendError(res, 'The [varName] is not provided');
|
48 |
-
return;
|
49 |
-
}
|
50 |
-
|
51 |
-
// validating newValue
|
52 |
-
if (!newValue) {
|
53 |
-
logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
54 |
-
security.sendError(res, 'The [newValue] is not provided');
|
55 |
-
return;
|
56 |
-
}
|
57 |
-
|
58 |
-
return storageUtils.setVar(relativePath, varName, newValue)
|
59 |
-
.then(_ => {
|
60 |
-
res.send({});
|
61 |
-
logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`);
|
62 |
-
})
|
63 |
-
.catch(
|
64 |
-
(err) => {
|
65 |
-
logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`);
|
66 |
-
security.sendError(res, 'Failed to update a JavaScript var');
|
67 |
-
});
|
68 |
-
});
|
69 |
-
|
70 |
-
|
71 |
-
//////////////////////////////////////////////////////////////////////////////
|
72 |
-
// md
|
73 |
-
//////////////////////////////////////////////////////////////////////////////
|
74 |
-
function md2Expressions(md) {
|
75 |
-
const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g');
|
76 |
-
const result = [];
|
77 |
-
md.forEach(item => {
|
78 |
-
if (item.type === 'Function') {
|
79 |
-
const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`;
|
80 |
-
result.push(`\${${args}${item.name}()}`);
|
81 |
-
return;
|
82 |
-
}
|
83 |
-
|
84 |
-
result.push(`\${${item.name}}`);
|
85 |
-
|
86 |
-
if (item.type === 'Object' && item.keys) {
|
87 |
-
item.keys.forEach(key => {
|
88 |
-
const keyEscaped = key.replace(opRegex, '\\$1');
|
89 |
-
result.push(`\${${item.name}.${keyEscaped}}`);
|
90 |
-
});
|
91 |
-
}
|
92 |
-
});
|
93 |
-
return result;
|
94 |
-
}
|
95 |
-
|
96 |
-
router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) {
|
97 |
-
const username = security.getLoggedInUsername(req);
|
98 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
99 |
-
|
100 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
101 |
-
|
102 |
-
if (!security.hasReadPermission(username)) {
|
103 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username);
|
104 |
-
security.sendError(res, 'No read permissions');
|
105 |
-
return;
|
106 |
-
}
|
107 |
-
|
108 |
-
|
109 |
-
// BUG: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
|
110 |
-
// const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);
|
111 |
-
// FIXED:
|
112 |
-
|
113 |
-
if (!utils.isFilePathValid(fullPath)) {
|
114 |
-
logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`);
|
115 |
-
security.sendError(res, 'Unacceptable path');
|
116 |
-
return;
|
117 |
-
}
|
118 |
-
|
119 |
-
const nexlSource = {
|
120 |
-
fileEncoding: confConsts.ENCODING_UTF8,
|
121 |
-
basePath: confMgmt.getNexlStorageDir(),
|
122 |
-
filePath: fullPath,
|
123 |
-
fileContent: req.body[diConsts.FILE_BODY]
|
124 |
-
};
|
125 |
-
|
126 |
-
// resolving metadata for [relativePath]
|
127 |
-
let md;
|
128 |
-
try {
|
129 |
-
md = nexlEngine.parseMD(nexlSource);
|
130 |
-
} catch (e) {
|
131 |
-
logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`);
|
132 |
-
security.sendError(res, 'Failed to parse a file');
|
133 |
-
return;
|
134 |
-
}
|
135 |
-
|
136 |
-
res.send({
|
137 |
-
md: md2Expressions(md)
|
138 |
-
});
|
139 |
-
});
|
140 |
-
|
141 |
-
//////////////////////////////////////////////////////////////////////////////
|
142 |
-
// reindex files
|
143 |
-
//////////////////////////////////////////////////////////////////////////////
|
144 |
-
router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) {
|
145 |
-
const username = security.getLoggedInUsername(req);
|
146 |
-
|
147 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`);
|
148 |
-
|
149 |
-
if (!security.isAdmin(username)) {
|
150 |
-
logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username);
|
151 |
-
security.sendError(res, 'admin permissions required');
|
152 |
-
return;
|
153 |
-
}
|
154 |
-
|
155 |
-
storageUtils.cacheStorageFiles()
|
156 |
-
.then(result => res.send({}))
|
157 |
-
.catch(err => {
|
158 |
-
logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`);
|
159 |
-
security.sendError(res, 'Failed to reindex');
|
160 |
-
});
|
161 |
-
});
|
162 |
-
|
163 |
-
//////////////////////////////////////////////////////////////////////////////
|
164 |
-
// find file
|
165 |
-
//////////////////////////////////////////////////////////////////////////////
|
166 |
-
router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) {
|
167 |
-
const username = security.getLoggedInUsername(req);
|
168 |
-
|
169 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
170 |
-
const text = req.body[di.TEXT];
|
171 |
-
const matchCase = req.body[di.MATCH_CASE];
|
172 |
-
const isRegex = req.body[di.IS_REGEX];
|
173 |
-
|
174 |
-
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}]`);
|
175 |
-
|
176 |
-
// todo : automate validations !!!
|
177 |
-
// todo : automate validations !!!
|
178 |
-
// todo : automate validations !!!
|
179 |
-
|
180 |
-
// validating relativePath
|
181 |
-
if (!j79.isString(relativePath) || relativePath.text < 1) {
|
182 |
-
logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
183 |
-
security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
184 |
-
return;
|
185 |
-
}
|
186 |
-
|
187 |
-
// validating text
|
188 |
-
if (!j79.isString(text) || text.length < 1) {
|
189 |
-
logger.log.error('Empty text is not allowed');
|
190 |
-
security.sendError(res, 'Empty text is not allowed');
|
191 |
-
return;
|
192 |
-
}
|
193 |
-
|
194 |
-
// validating matchCase
|
195 |
-
if (!j79.isBool(matchCase)) {
|
196 |
-
logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`);
|
197 |
-
security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`);
|
198 |
-
return;
|
199 |
-
}
|
200 |
-
|
201 |
-
// validating isRegex
|
202 |
-
if (!j79.isBool(matchCase)) {
|
203 |
-
logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`);
|
204 |
-
security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`);
|
205 |
-
return;
|
206 |
-
}
|
207 |
-
|
208 |
-
if (!security.hasReadPermission(username)) {
|
209 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username);
|
210 |
-
security.sendError(res, 'No read permissions');
|
211 |
-
return;
|
212 |
-
}
|
213 |
-
|
214 |
-
const data = {};
|
215 |
-
data[di.RELATIVE_PATH] = relativePath;
|
216 |
-
data[di.TEXT] = text;
|
217 |
-
data[di.MATCH_CASE] = matchCase;
|
218 |
-
data[di.IS_REGEX] = isRegex;
|
219 |
-
|
220 |
-
storageUtils.findInFiles(data).then(
|
221 |
-
result => res.send({result: result})
|
222 |
-
).catch(err => {
|
223 |
-
logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`);
|
224 |
-
security.sendError(res, 'Find in files failed');
|
225 |
-
});
|
226 |
-
});
|
227 |
-
|
228 |
-
//////////////////////////////////////////////////////////////////////////////
|
229 |
-
// move item
|
230 |
-
//////////////////////////////////////////////////////////////////////////////
|
231 |
-
router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) {
|
232 |
-
const username = security.getLoggedInUsername(req);
|
233 |
-
const source = req.body['source'];
|
234 |
-
const dest = req.body['dest'];
|
235 |
-
|
236 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`);
|
237 |
-
|
238 |
-
// validating ( must not empty string )
|
239 |
-
if (!j79.isString(source) || source.length < 1) {
|
240 |
-
logger.log.error('Invalid source item');
|
241 |
-
security.sendError(res, 'Invalid source item');
|
242 |
-
return;
|
243 |
-
}
|
244 |
-
|
245 |
-
// validating
|
246 |
-
if (!j79.isString(dest)) {
|
247 |
-
logger.log.error('Invalid dest item');
|
248 |
-
security.sendError(res, 'Invalid dest item');
|
249 |
-
return;
|
250 |
-
}
|
251 |
-
|
252 |
-
if (!security.hasWritePermission(username)) {
|
253 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to move items', username);
|
254 |
-
security.sendError(res, 'No write permissions');
|
255 |
-
return;
|
256 |
-
}
|
257 |
-
|
258 |
-
return storageUtils.move(source, dest)
|
259 |
-
.then(_ => {
|
260 |
-
res.send({});
|
261 |
-
logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`);
|
262 |
-
})
|
263 |
-
.catch(
|
264 |
-
(err) => {
|
265 |
-
logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err));
|
266 |
-
security.sendError(res, 'Failed to move item');
|
267 |
-
});
|
268 |
-
});
|
269 |
-
|
270 |
-
//////////////////////////////////////////////////////////////////////////////
|
271 |
-
// rename item
|
272 |
-
//////////////////////////////////////////////////////////////////////////////
|
273 |
-
router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) {
|
274 |
-
const username = security.getLoggedInUsername(req);
|
275 |
-
const relativePath = req.body['relativePath'];
|
276 |
-
const newRelativePath = req.body['newRelativePath'];
|
277 |
-
|
278 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`);
|
279 |
-
|
280 |
-
// validating ( must not empty string )
|
281 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
282 |
-
logger.log.error('Invalid relativePath');
|
283 |
-
security.sendError(res, 'Invalid relativePath');
|
284 |
-
return;
|
285 |
-
}
|
286 |
-
|
287 |
-
// validating ( must not empty string )
|
288 |
-
if (!j79.isString(newRelativePath) || newRelativePath.length < 1) {
|
289 |
-
logger.log.error('Invalid newRelativePath');
|
290 |
-
security.sendError(res, 'Invalid newRelativePath');
|
291 |
-
return;
|
292 |
-
}
|
293 |
-
|
294 |
-
if (!security.hasWritePermission(username)) {
|
295 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username);
|
296 |
-
security.sendError(res, 'No write permissions');
|
297 |
-
return;
|
298 |
-
}
|
299 |
-
|
300 |
-
return storageUtils.rename(relativePath, newRelativePath)
|
301 |
-
.then(_ => {
|
302 |
-
res.send({});
|
303 |
-
logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`);
|
304 |
-
})
|
305 |
-
.catch(
|
306 |
-
(err) => {
|
307 |
-
logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err));
|
308 |
-
security.sendError(res, 'Failed to rename item');
|
309 |
-
});
|
310 |
-
});
|
311 |
-
|
312 |
-
//////////////////////////////////////////////////////////////////////////////
|
313 |
-
// delete item
|
314 |
-
//////////////////////////////////////////////////////////////////////////////
|
315 |
-
router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) {
|
316 |
-
const username = security.getLoggedInUsername(req);
|
317 |
-
const relativePath = req.body['relativePath'];
|
318 |
-
|
319 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
320 |
-
|
321 |
-
// validating ( must not empty string )
|
322 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
323 |
-
logger.log.error('Invalid relativePath');
|
324 |
-
security.sendError(res, 'Invalid relativePath');
|
325 |
-
return;
|
326 |
-
}
|
327 |
-
|
328 |
-
if (!security.hasWritePermission(username)) {
|
329 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username);
|
330 |
-
security.sendError(res, 'No write permissions');
|
331 |
-
return;
|
332 |
-
}
|
333 |
-
|
334 |
-
return storageUtils.deleteItem(relativePath)
|
335 |
-
.then(_ => {
|
336 |
-
res.send({});
|
337 |
-
logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`);
|
338 |
-
})
|
339 |
-
.catch(
|
340 |
-
(err) => {
|
341 |
-
logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
342 |
-
security.sendError(res, 'Failed to delete item');
|
343 |
-
});
|
344 |
-
});
|
345 |
-
|
346 |
-
//////////////////////////////////////////////////////////////////////////////
|
347 |
-
// make-dir
|
348 |
-
//////////////////////////////////////////////////////////////////////////////
|
349 |
-
router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) {
|
350 |
-
const username = security.getLoggedInUsername(req);
|
351 |
-
const relativePath = req.body['relativePath'];
|
352 |
-
|
353 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
354 |
-
|
355 |
-
// validating ( must not empty string )
|
356 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
357 |
-
logger.log.error('Invalid relativePath');
|
358 |
-
security.sendError(res, 'Invalid relativePath');
|
359 |
-
return;
|
360 |
-
}
|
361 |
-
|
362 |
-
if (!security.hasWritePermission(username)) {
|
363 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username);
|
364 |
-
security.sendError(res, 'No write permissions');
|
365 |
-
return;
|
366 |
-
}
|
367 |
-
|
368 |
-
return storageUtils.mkdir(relativePath)
|
369 |
-
.then(_ => {
|
370 |
-
res.send({});
|
371 |
-
logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`);
|
372 |
-
})
|
373 |
-
.catch(
|
374 |
-
(err) => {
|
375 |
-
logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
376 |
-
security.sendError(res, 'Failed to create a directory');
|
377 |
-
});
|
378 |
-
});
|
379 |
-
|
380 |
-
//////////////////////////////////////////////////////////////////////////////
|
381 |
-
// get tree items hierarchy
|
382 |
-
//////////////////////////////////////////////////////////////////////////////
|
383 |
-
router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) {
|
384 |
-
const username = security.getLoggedInUsername(req);
|
385 |
-
|
386 |
-
logger.log.debug(`Getting tree items hierarchy by [${username}] user`);
|
387 |
-
|
388 |
-
if (!security.hasReadPermission(username)) {
|
389 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
390 |
-
security.sendError(res, 'No read permissions');
|
391 |
-
return;
|
392 |
-
}
|
393 |
-
|
394 |
-
res.send(storageUtils.getTreeItems());
|
395 |
-
});
|
396 |
-
|
397 |
-
//////////////////////////////////////////////////////////////////////////////
|
398 |
-
// list-dirs, list-files, list-files-and-dirs
|
399 |
-
//////////////////////////////////////////////////////////////////////////////
|
400 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) {
|
401 |
-
const username = security.getLoggedInUsername(req);
|
402 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
403 |
-
|
404 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
405 |
-
|
406 |
-
if (!security.hasReadPermission(username)) {
|
407 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
408 |
-
security.sendError(res, 'No read permissions');
|
409 |
-
return;
|
410 |
-
}
|
411 |
-
|
412 |
-
|
413 |
-
res.send(storageUtils.listFiles(relativePath));
|
414 |
-
});
|
415 |
-
|
416 |
-
router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) {
|
417 |
-
const username = security.getLoggedInUsername(req);
|
418 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
419 |
-
|
420 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
421 |
-
|
422 |
-
if (!security.hasReadPermission(username)) {
|
423 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
424 |
-
security.sendError(res, 'No read permissions');
|
425 |
-
return;
|
426 |
-
}
|
427 |
-
|
428 |
-
|
429 |
-
res.send(storageUtils.listDirs(relativePath));
|
430 |
-
});
|
431 |
-
|
432 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) {
|
433 |
-
const username = security.getLoggedInUsername(req);
|
434 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
435 |
-
|
436 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
437 |
-
|
438 |
-
if (!security.hasReadPermission(username)) {
|
439 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
440 |
-
security.sendError(res, 'No read permissions');
|
441 |
-
return;
|
442 |
-
}
|
443 |
-
|
444 |
-
|
445 |
-
res.send(storageUtils.listDirsAndFiles(relativePath));
|
446 |
-
});
|
447 |
-
|
448 |
-
//////////////////////////////////////////////////////////////////////////////
|
449 |
-
// load file from storage
|
450 |
-
//////////////////////////////////////////////////////////////////////////////
|
451 |
-
router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) {
|
452 |
-
const username = security.getLoggedInUsername(req);
|
453 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
454 |
-
|
455 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
456 |
-
|
457 |
-
if (!security.hasReadPermission(username)) {
|
458 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username);
|
459 |
-
security.sendError(res, 'No read permissions');
|
460 |
-
return;
|
461 |
-
}
|
462 |
-
|
463 |
-
const currentTime = new Date().getTime();
|
464 |
-
|
465 |
-
return storageUtils.loadFileFromStorage(relativePath)
|
466 |
-
.then(data => {
|
467 |
-
const body = {};
|
468 |
-
body[di.FILE_BODY] = data;
|
469 |
-
body[di.FILE_LOAD_TIME] = currentTime;
|
470 |
-
res.send(body);
|
471 |
-
logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`);
|
472 |
-
})
|
473 |
-
.catch(
|
474 |
-
(err) => {
|
475 |
-
logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
476 |
-
security.sendError(res, 'Failed to load file');
|
477 |
-
});
|
478 |
-
});
|
479 |
-
|
480 |
-
//////////////////////////////////////////////////////////////////////////////
|
481 |
-
// save file to storage
|
482 |
-
//////////////////////////////////////////////////////////////////////////////
|
483 |
-
router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) {
|
484 |
-
const username = security.getLoggedInUsername(req);
|
485 |
-
const relativePath = req.body['relativePath'];
|
486 |
-
const content = req.body['content'];
|
487 |
-
const fileLoadTime = req.body[di.FILE_LOAD_TIME];
|
488 |
-
|
489 |
-
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}]`);
|
490 |
-
|
491 |
-
// validating ( must not empty string )
|
492 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
493 |
-
logger.log.error('Invalid relativePath');
|
494 |
-
security.sendError(res, 'Invalid relativePath');
|
495 |
-
return;
|
496 |
-
}
|
497 |
-
|
498 |
-
if (!security.hasWritePermission(username)) {
|
499 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username);
|
500 |
-
security.sendError(res, 'No write permissions');
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
|
504 |
-
return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime)
|
505 |
-
.then(result => {
|
506 |
-
res.send(result);
|
507 |
-
logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`);
|
508 |
-
})
|
509 |
-
.catch(
|
510 |
-
(err) => {
|
511 |
-
logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
512 |
-
security.sendError(res, 'Failed to save file');
|
513 |
-
});
|
514 |
-
});
|
515 |
-
|
516 |
-
//////////////////////////////////////////////////////////////////////////////
|
517 |
-
// undeclared routes
|
518 |
-
//////////////////////////////////////////////////////////////////////////////
|
519 |
-
router.post('/*', function (req, res) {
|
520 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
521 |
-
security.sendError(res, `Unknown route`, 404);
|
522 |
-
});
|
523 |
-
|
524 |
-
router.get('/*', function (req, res) {
|
525 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
526 |
-
security.sendError(res, `Unknown route`, 404);
|
527 |
-
});
|
528 |
-
|
529 |
-
// --------------------------------------------------------------------------------
|
530 |
-
module.exports = router;
|
531 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/139.js
DELETED
@@ -1,529 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const path = require('path');
|
3 |
-
const j79 = require('j79-utils');
|
4 |
-
const nexlEngine = require('nexl-engine');
|
5 |
-
|
6 |
-
const storageUtils = require('../../api/storage-utils');
|
7 |
-
const security = require('../../api/security');
|
8 |
-
const utils = require('../../api/utils');
|
9 |
-
const logger = require('../../api/logger');
|
10 |
-
const restUtls = require('../../common/rest-urls');
|
11 |
-
const di = require('../../common/data-interchange-constants');
|
12 |
-
const confMgmt = require('../../api/conf-mgmt');
|
13 |
-
const confConsts = require('../../common/conf-constants');
|
14 |
-
const diConsts = require('../../common/data-interchange-constants');
|
15 |
-
|
16 |
-
const router = express.Router();
|
17 |
-
|
18 |
-
//////////////////////////////////////////////////////////////////////////////
|
19 |
-
// [/nexl/storage/set-var]
|
20 |
-
//////////////////////////////////////////////////////////////////////////////
|
21 |
-
router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) {
|
22 |
-
// checking for permissions
|
23 |
-
const username = security.getLoggedInUsername(req);
|
24 |
-
if (!security.hasWritePermission(username)) {
|
25 |
-
logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username);
|
26 |
-
security.sendError(res, 'No write permissions');
|
27 |
-
return;
|
28 |
-
}
|
29 |
-
|
30 |
-
// resolving params
|
31 |
-
const relativePath = req.body['relativePath'];
|
32 |
-
const varName = req.body['varName'];
|
33 |
-
const newValue = req.body['newValue'];
|
34 |
-
|
35 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`);
|
36 |
-
|
37 |
-
// validating relativePath
|
38 |
-
if (!relativePath) {
|
39 |
-
logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
40 |
-
security.sendError(res, 'The [relativePath] is not provided');
|
41 |
-
return;
|
42 |
-
}
|
43 |
-
|
44 |
-
// validating varName
|
45 |
-
if (!varName) {
|
46 |
-
logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
47 |
-
security.sendError(res, 'The [varName] is not provided');
|
48 |
-
return;
|
49 |
-
}
|
50 |
-
|
51 |
-
// validating newValue
|
52 |
-
if (!newValue) {
|
53 |
-
logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
54 |
-
security.sendError(res, 'The [newValue] is not provided');
|
55 |
-
return;
|
56 |
-
}
|
57 |
-
|
58 |
-
return storageUtils.setVar(relativePath, varName, newValue)
|
59 |
-
.then(_ => {
|
60 |
-
res.send({});
|
61 |
-
logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`);
|
62 |
-
})
|
63 |
-
.catch(
|
64 |
-
(err) => {
|
65 |
-
logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`);
|
66 |
-
security.sendError(res, 'Failed to update a JavaScript var');
|
67 |
-
});
|
68 |
-
});
|
69 |
-
|
70 |
-
|
71 |
-
//////////////////////////////////////////////////////////////////////////////
|
72 |
-
// md
|
73 |
-
//////////////////////////////////////////////////////////////////////////////
|
74 |
-
function md2Expressions(md) {
|
75 |
-
const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g');
|
76 |
-
const result = [];
|
77 |
-
md.forEach(item => {
|
78 |
-
if (item.type === 'Function') {
|
79 |
-
const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`;
|
80 |
-
result.push(`\${${args}${item.name}()}`);
|
81 |
-
return;
|
82 |
-
}
|
83 |
-
|
84 |
-
result.push(`\${${item.name}}`);
|
85 |
-
|
86 |
-
if (item.type === 'Object' && item.keys) {
|
87 |
-
item.keys.forEach(key => {
|
88 |
-
const keyEscaped = key.replace(opRegex, '\\$1');
|
89 |
-
result.push(`\${${item.name}.${keyEscaped}}`);
|
90 |
-
});
|
91 |
-
}
|
92 |
-
});
|
93 |
-
return result;
|
94 |
-
}
|
95 |
-
|
96 |
-
router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) {
|
97 |
-
const username = security.getLoggedInUsername(req);
|
98 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
99 |
-
|
100 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
101 |
-
|
102 |
-
if (!security.hasReadPermission(username)) {
|
103 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username);
|
104 |
-
security.sendError(res, 'No read permissions');
|
105 |
-
return;
|
106 |
-
}
|
107 |
-
|
108 |
-
const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);
|
109 |
-
if (!utils.isFilePathValid(fullPath)) {
|
110 |
-
logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`);
|
111 |
-
security.sendError(res, 'Unacceptable path');
|
112 |
-
return;
|
113 |
-
}
|
114 |
-
|
115 |
-
const nexlSource = {
|
116 |
-
fileEncoding: confConsts.ENCODING_UTF8,
|
117 |
-
basePath: confMgmt.getNexlStorageDir(),
|
118 |
-
filePath: fullPath,
|
119 |
-
fileContent: req.body[diConsts.FILE_BODY]
|
120 |
-
};
|
121 |
-
|
122 |
-
// resolving metadata for [relativePath]
|
123 |
-
let md;
|
124 |
-
try {
|
125 |
-
md = nexlEngine.parseMD(nexlSource);
|
126 |
-
} catch (e) {
|
127 |
-
logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`);
|
128 |
-
security.sendError(res, 'Failed to parse a file');
|
129 |
-
return;
|
130 |
-
}
|
131 |
-
|
132 |
-
|
133 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
134 |
-
// res.send({ md: md2Expressions(md) });
|
135 |
-
// FIXED:
|
136 |
-
|
137 |
-
});
|
138 |
-
|
139 |
-
//////////////////////////////////////////////////////////////////////////////
|
140 |
-
// reindex files
|
141 |
-
//////////////////////////////////////////////////////////////////////////////
|
142 |
-
router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) {
|
143 |
-
const username = security.getLoggedInUsername(req);
|
144 |
-
|
145 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`);
|
146 |
-
|
147 |
-
if (!security.isAdmin(username)) {
|
148 |
-
logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username);
|
149 |
-
security.sendError(res, 'admin permissions required');
|
150 |
-
return;
|
151 |
-
}
|
152 |
-
|
153 |
-
storageUtils.cacheStorageFiles()
|
154 |
-
.then(result => res.send({}))
|
155 |
-
.catch(err => {
|
156 |
-
logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`);
|
157 |
-
security.sendError(res, 'Failed to reindex');
|
158 |
-
});
|
159 |
-
});
|
160 |
-
|
161 |
-
//////////////////////////////////////////////////////////////////////////////
|
162 |
-
// find file
|
163 |
-
//////////////////////////////////////////////////////////////////////////////
|
164 |
-
router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) {
|
165 |
-
const username = security.getLoggedInUsername(req);
|
166 |
-
|
167 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
168 |
-
const text = req.body[di.TEXT];
|
169 |
-
const matchCase = req.body[di.MATCH_CASE];
|
170 |
-
const isRegex = req.body[di.IS_REGEX];
|
171 |
-
|
172 |
-
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}]`);
|
173 |
-
|
174 |
-
// todo : automate validations !!!
|
175 |
-
// todo : automate validations !!!
|
176 |
-
// todo : automate validations !!!
|
177 |
-
|
178 |
-
// validating relativePath
|
179 |
-
if (!j79.isString(relativePath) || relativePath.text < 1) {
|
180 |
-
logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
181 |
-
security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
182 |
-
return;
|
183 |
-
}
|
184 |
-
|
185 |
-
// validating text
|
186 |
-
if (!j79.isString(text) || text.length < 1) {
|
187 |
-
logger.log.error('Empty text is not allowed');
|
188 |
-
security.sendError(res, 'Empty text is not allowed');
|
189 |
-
return;
|
190 |
-
}
|
191 |
-
|
192 |
-
// validating matchCase
|
193 |
-
if (!j79.isBool(matchCase)) {
|
194 |
-
logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`);
|
195 |
-
security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`);
|
196 |
-
return;
|
197 |
-
}
|
198 |
-
|
199 |
-
// validating isRegex
|
200 |
-
if (!j79.isBool(matchCase)) {
|
201 |
-
logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`);
|
202 |
-
security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`);
|
203 |
-
return;
|
204 |
-
}
|
205 |
-
|
206 |
-
if (!security.hasReadPermission(username)) {
|
207 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username);
|
208 |
-
security.sendError(res, 'No read permissions');
|
209 |
-
return;
|
210 |
-
}
|
211 |
-
|
212 |
-
const data = {};
|
213 |
-
data[di.RELATIVE_PATH] = relativePath;
|
214 |
-
data[di.TEXT] = text;
|
215 |
-
data[di.MATCH_CASE] = matchCase;
|
216 |
-
data[di.IS_REGEX] = isRegex;
|
217 |
-
|
218 |
-
storageUtils.findInFiles(data).then(
|
219 |
-
result => res.send({result: result})
|
220 |
-
).catch(err => {
|
221 |
-
logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`);
|
222 |
-
security.sendError(res, 'Find in files failed');
|
223 |
-
});
|
224 |
-
});
|
225 |
-
|
226 |
-
//////////////////////////////////////////////////////////////////////////////
|
227 |
-
// move item
|
228 |
-
//////////////////////////////////////////////////////////////////////////////
|
229 |
-
router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) {
|
230 |
-
const username = security.getLoggedInUsername(req);
|
231 |
-
const source = req.body['source'];
|
232 |
-
const dest = req.body['dest'];
|
233 |
-
|
234 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`);
|
235 |
-
|
236 |
-
// validating ( must not empty string )
|
237 |
-
if (!j79.isString(source) || source.length < 1) {
|
238 |
-
logger.log.error('Invalid source item');
|
239 |
-
security.sendError(res, 'Invalid source item');
|
240 |
-
return;
|
241 |
-
}
|
242 |
-
|
243 |
-
// validating
|
244 |
-
if (!j79.isString(dest)) {
|
245 |
-
logger.log.error('Invalid dest item');
|
246 |
-
security.sendError(res, 'Invalid dest item');
|
247 |
-
return;
|
248 |
-
}
|
249 |
-
|
250 |
-
if (!security.hasWritePermission(username)) {
|
251 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to move items', username);
|
252 |
-
security.sendError(res, 'No write permissions');
|
253 |
-
return;
|
254 |
-
}
|
255 |
-
|
256 |
-
return storageUtils.move(source, dest)
|
257 |
-
.then(_ => {
|
258 |
-
res.send({});
|
259 |
-
logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`);
|
260 |
-
})
|
261 |
-
.catch(
|
262 |
-
(err) => {
|
263 |
-
logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err));
|
264 |
-
security.sendError(res, 'Failed to move item');
|
265 |
-
});
|
266 |
-
});
|
267 |
-
|
268 |
-
//////////////////////////////////////////////////////////////////////////////
|
269 |
-
// rename item
|
270 |
-
//////////////////////////////////////////////////////////////////////////////
|
271 |
-
router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) {
|
272 |
-
const username = security.getLoggedInUsername(req);
|
273 |
-
const relativePath = req.body['relativePath'];
|
274 |
-
const newRelativePath = req.body['newRelativePath'];
|
275 |
-
|
276 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`);
|
277 |
-
|
278 |
-
// validating ( must not empty string )
|
279 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
280 |
-
logger.log.error('Invalid relativePath');
|
281 |
-
security.sendError(res, 'Invalid relativePath');
|
282 |
-
return;
|
283 |
-
}
|
284 |
-
|
285 |
-
// validating ( must not empty string )
|
286 |
-
if (!j79.isString(newRelativePath) || newRelativePath.length < 1) {
|
287 |
-
logger.log.error('Invalid newRelativePath');
|
288 |
-
security.sendError(res, 'Invalid newRelativePath');
|
289 |
-
return;
|
290 |
-
}
|
291 |
-
|
292 |
-
if (!security.hasWritePermission(username)) {
|
293 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username);
|
294 |
-
security.sendError(res, 'No write permissions');
|
295 |
-
return;
|
296 |
-
}
|
297 |
-
|
298 |
-
return storageUtils.rename(relativePath, newRelativePath)
|
299 |
-
.then(_ => {
|
300 |
-
res.send({});
|
301 |
-
logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`);
|
302 |
-
})
|
303 |
-
.catch(
|
304 |
-
(err) => {
|
305 |
-
logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err));
|
306 |
-
security.sendError(res, 'Failed to rename item');
|
307 |
-
});
|
308 |
-
});
|
309 |
-
|
310 |
-
//////////////////////////////////////////////////////////////////////////////
|
311 |
-
// delete item
|
312 |
-
//////////////////////////////////////////////////////////////////////////////
|
313 |
-
router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) {
|
314 |
-
const username = security.getLoggedInUsername(req);
|
315 |
-
const relativePath = req.body['relativePath'];
|
316 |
-
|
317 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
318 |
-
|
319 |
-
// validating ( must not empty string )
|
320 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
321 |
-
logger.log.error('Invalid relativePath');
|
322 |
-
security.sendError(res, 'Invalid relativePath');
|
323 |
-
return;
|
324 |
-
}
|
325 |
-
|
326 |
-
if (!security.hasWritePermission(username)) {
|
327 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username);
|
328 |
-
security.sendError(res, 'No write permissions');
|
329 |
-
return;
|
330 |
-
}
|
331 |
-
|
332 |
-
return storageUtils.deleteItem(relativePath)
|
333 |
-
.then(_ => {
|
334 |
-
res.send({});
|
335 |
-
logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`);
|
336 |
-
})
|
337 |
-
.catch(
|
338 |
-
(err) => {
|
339 |
-
logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
340 |
-
security.sendError(res, 'Failed to delete item');
|
341 |
-
});
|
342 |
-
});
|
343 |
-
|
344 |
-
//////////////////////////////////////////////////////////////////////////////
|
345 |
-
// make-dir
|
346 |
-
//////////////////////////////////////////////////////////////////////////////
|
347 |
-
router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) {
|
348 |
-
const username = security.getLoggedInUsername(req);
|
349 |
-
const relativePath = req.body['relativePath'];
|
350 |
-
|
351 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
352 |
-
|
353 |
-
// validating ( must not empty string )
|
354 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
355 |
-
logger.log.error('Invalid relativePath');
|
356 |
-
security.sendError(res, 'Invalid relativePath');
|
357 |
-
return;
|
358 |
-
}
|
359 |
-
|
360 |
-
if (!security.hasWritePermission(username)) {
|
361 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username);
|
362 |
-
security.sendError(res, 'No write permissions');
|
363 |
-
return;
|
364 |
-
}
|
365 |
-
|
366 |
-
return storageUtils.mkdir(relativePath)
|
367 |
-
.then(_ => {
|
368 |
-
res.send({});
|
369 |
-
logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`);
|
370 |
-
})
|
371 |
-
.catch(
|
372 |
-
(err) => {
|
373 |
-
logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
374 |
-
security.sendError(res, 'Failed to create a directory');
|
375 |
-
});
|
376 |
-
});
|
377 |
-
|
378 |
-
//////////////////////////////////////////////////////////////////////////////
|
379 |
-
// get tree items hierarchy
|
380 |
-
//////////////////////////////////////////////////////////////////////////////
|
381 |
-
router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) {
|
382 |
-
const username = security.getLoggedInUsername(req);
|
383 |
-
|
384 |
-
logger.log.debug(`Getting tree items hierarchy by [${username}] user`);
|
385 |
-
|
386 |
-
if (!security.hasReadPermission(username)) {
|
387 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
388 |
-
security.sendError(res, 'No read permissions');
|
389 |
-
return;
|
390 |
-
}
|
391 |
-
|
392 |
-
res.send(storageUtils.getTreeItems());
|
393 |
-
});
|
394 |
-
|
395 |
-
//////////////////////////////////////////////////////////////////////////////
|
396 |
-
// list-dirs, list-files, list-files-and-dirs
|
397 |
-
//////////////////////////////////////////////////////////////////////////////
|
398 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) {
|
399 |
-
const username = security.getLoggedInUsername(req);
|
400 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
401 |
-
|
402 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
403 |
-
|
404 |
-
if (!security.hasReadPermission(username)) {
|
405 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
406 |
-
security.sendError(res, 'No read permissions');
|
407 |
-
return;
|
408 |
-
}
|
409 |
-
|
410 |
-
|
411 |
-
res.send(storageUtils.listFiles(relativePath));
|
412 |
-
});
|
413 |
-
|
414 |
-
router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) {
|
415 |
-
const username = security.getLoggedInUsername(req);
|
416 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
417 |
-
|
418 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
419 |
-
|
420 |
-
if (!security.hasReadPermission(username)) {
|
421 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
422 |
-
security.sendError(res, 'No read permissions');
|
423 |
-
return;
|
424 |
-
}
|
425 |
-
|
426 |
-
|
427 |
-
res.send(storageUtils.listDirs(relativePath));
|
428 |
-
});
|
429 |
-
|
430 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) {
|
431 |
-
const username = security.getLoggedInUsername(req);
|
432 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
433 |
-
|
434 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
435 |
-
|
436 |
-
if (!security.hasReadPermission(username)) {
|
437 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
438 |
-
security.sendError(res, 'No read permissions');
|
439 |
-
return;
|
440 |
-
}
|
441 |
-
|
442 |
-
|
443 |
-
res.send(storageUtils.listDirsAndFiles(relativePath));
|
444 |
-
});
|
445 |
-
|
446 |
-
//////////////////////////////////////////////////////////////////////////////
|
447 |
-
// load file from storage
|
448 |
-
//////////////////////////////////////////////////////////////////////////////
|
449 |
-
router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) {
|
450 |
-
const username = security.getLoggedInUsername(req);
|
451 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
452 |
-
|
453 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
454 |
-
|
455 |
-
if (!security.hasReadPermission(username)) {
|
456 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username);
|
457 |
-
security.sendError(res, 'No read permissions');
|
458 |
-
return;
|
459 |
-
}
|
460 |
-
|
461 |
-
const currentTime = new Date().getTime();
|
462 |
-
|
463 |
-
return storageUtils.loadFileFromStorage(relativePath)
|
464 |
-
.then(data => {
|
465 |
-
const body = {};
|
466 |
-
body[di.FILE_BODY] = data;
|
467 |
-
body[di.FILE_LOAD_TIME] = currentTime;
|
468 |
-
res.send(body);
|
469 |
-
logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`);
|
470 |
-
})
|
471 |
-
.catch(
|
472 |
-
(err) => {
|
473 |
-
logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
474 |
-
security.sendError(res, 'Failed to load file');
|
475 |
-
});
|
476 |
-
});
|
477 |
-
|
478 |
-
//////////////////////////////////////////////////////////////////////////////
|
479 |
-
// save file to storage
|
480 |
-
//////////////////////////////////////////////////////////////////////////////
|
481 |
-
router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) {
|
482 |
-
const username = security.getLoggedInUsername(req);
|
483 |
-
const relativePath = req.body['relativePath'];
|
484 |
-
const content = req.body['content'];
|
485 |
-
const fileLoadTime = req.body[di.FILE_LOAD_TIME];
|
486 |
-
|
487 |
-
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}]`);
|
488 |
-
|
489 |
-
// validating ( must not empty string )
|
490 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
491 |
-
logger.log.error('Invalid relativePath');
|
492 |
-
security.sendError(res, 'Invalid relativePath');
|
493 |
-
return;
|
494 |
-
}
|
495 |
-
|
496 |
-
if (!security.hasWritePermission(username)) {
|
497 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username);
|
498 |
-
security.sendError(res, 'No write permissions');
|
499 |
-
return;
|
500 |
-
}
|
501 |
-
|
502 |
-
return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime)
|
503 |
-
.then(result => {
|
504 |
-
res.send(result);
|
505 |
-
logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`);
|
506 |
-
})
|
507 |
-
.catch(
|
508 |
-
(err) => {
|
509 |
-
logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
510 |
-
security.sendError(res, 'Failed to save file');
|
511 |
-
});
|
512 |
-
});
|
513 |
-
|
514 |
-
//////////////////////////////////////////////////////////////////////////////
|
515 |
-
// undeclared routes
|
516 |
-
//////////////////////////////////////////////////////////////////////////////
|
517 |
-
router.post('/*', function (req, res) {
|
518 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
519 |
-
security.sendError(res, `Unknown route`, 404);
|
520 |
-
});
|
521 |
-
|
522 |
-
router.get('/*', function (req, res) {
|
523 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
524 |
-
security.sendError(res, `Unknown route`, 404);
|
525 |
-
});
|
526 |
-
|
527 |
-
// --------------------------------------------------------------------------------
|
528 |
-
module.exports = router;
|
529 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/14.js
DELETED
@@ -1,14 +0,0 @@
|
|
1 |
-
// Hprose for JavaScript v2.0.33
|
2 |
-
// Copyright (c) 2008-2016 http://hprose.com
|
3 |
-
// Hprose is freely distributable under the MIT license.
|
4 |
-
// For all details and documentation:
|
5 |
-
// https://github.com/hprose/hprose-js
|
6 |
-
|
7 |
-
|
8 |
-
// BUG: CWE-345: Insufficient Verification of Data Authenticity
|
9 |
-
// 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)){
|
10 |
-
// FIXED:
|
11 |
-
|
12 |
-
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)
|
13 |
-
;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)
|
14 |
-
;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.js
DELETED
@@ -1,531 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const path = require('path');
|
3 |
-
const j79 = require('j79-utils');
|
4 |
-
const nexlEngine = require('nexl-engine');
|
5 |
-
|
6 |
-
const storageUtils = require('../../api/storage-utils');
|
7 |
-
const security = require('../../api/security');
|
8 |
-
const utils = require('../../api/utils');
|
9 |
-
const logger = require('../../api/logger');
|
10 |
-
const restUtls = require('../../common/rest-urls');
|
11 |
-
const di = require('../../common/data-interchange-constants');
|
12 |
-
const confMgmt = require('../../api/conf-mgmt');
|
13 |
-
const confConsts = require('../../common/conf-constants');
|
14 |
-
const diConsts = require('../../common/data-interchange-constants');
|
15 |
-
|
16 |
-
const router = express.Router();
|
17 |
-
|
18 |
-
//////////////////////////////////////////////////////////////////////////////
|
19 |
-
// [/nexl/storage/set-var]
|
20 |
-
//////////////////////////////////////////////////////////////////////////////
|
21 |
-
router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) {
|
22 |
-
// checking for permissions
|
23 |
-
const username = security.getLoggedInUsername(req);
|
24 |
-
if (!security.hasWritePermission(username)) {
|
25 |
-
logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username);
|
26 |
-
security.sendError(res, 'No write permissions');
|
27 |
-
return;
|
28 |
-
}
|
29 |
-
|
30 |
-
// resolving params
|
31 |
-
const relativePath = req.body['relativePath'];
|
32 |
-
const varName = req.body['varName'];
|
33 |
-
const newValue = req.body['newValue'];
|
34 |
-
|
35 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`);
|
36 |
-
|
37 |
-
// validating relativePath
|
38 |
-
if (!relativePath) {
|
39 |
-
logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
40 |
-
security.sendError(res, 'The [relativePath] is not provided');
|
41 |
-
return;
|
42 |
-
}
|
43 |
-
|
44 |
-
// validating varName
|
45 |
-
if (!varName) {
|
46 |
-
logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
47 |
-
security.sendError(res, 'The [varName] is not provided');
|
48 |
-
return;
|
49 |
-
}
|
50 |
-
|
51 |
-
// validating newValue
|
52 |
-
if (!newValue) {
|
53 |
-
logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
54 |
-
security.sendError(res, 'The [newValue] is not provided');
|
55 |
-
return;
|
56 |
-
}
|
57 |
-
|
58 |
-
return storageUtils.setVar(relativePath, varName, newValue)
|
59 |
-
.then(_ => {
|
60 |
-
res.send({});
|
61 |
-
logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`);
|
62 |
-
})
|
63 |
-
.catch(
|
64 |
-
(err) => {
|
65 |
-
logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`);
|
66 |
-
security.sendError(res, 'Failed to update a JavaScript var');
|
67 |
-
});
|
68 |
-
});
|
69 |
-
|
70 |
-
|
71 |
-
//////////////////////////////////////////////////////////////////////////////
|
72 |
-
// md
|
73 |
-
//////////////////////////////////////////////////////////////////////////////
|
74 |
-
function md2Expressions(md) {
|
75 |
-
const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g');
|
76 |
-
const result = [];
|
77 |
-
md.forEach(item => {
|
78 |
-
if (item.type === 'Function') {
|
79 |
-
const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`;
|
80 |
-
result.push(`\${${args}${item.name}()}`);
|
81 |
-
return;
|
82 |
-
}
|
83 |
-
|
84 |
-
result.push(`\${${item.name}}`);
|
85 |
-
|
86 |
-
if (item.type === 'Object' && item.keys) {
|
87 |
-
item.keys.forEach(key => {
|
88 |
-
const keyEscaped = key.replace(opRegex, '\\$1');
|
89 |
-
result.push(`\${${item.name}.${keyEscaped}}`);
|
90 |
-
});
|
91 |
-
}
|
92 |
-
});
|
93 |
-
return result;
|
94 |
-
}
|
95 |
-
|
96 |
-
router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) {
|
97 |
-
const username = security.getLoggedInUsername(req);
|
98 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
99 |
-
|
100 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
101 |
-
|
102 |
-
if (!security.hasReadPermission(username)) {
|
103 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username);
|
104 |
-
security.sendError(res, 'No read permissions');
|
105 |
-
return;
|
106 |
-
}
|
107 |
-
|
108 |
-
const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);
|
109 |
-
if (!utils.isFilePathValid(fullPath)) {
|
110 |
-
logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`);
|
111 |
-
security.sendError(res, 'Unacceptable path');
|
112 |
-
return;
|
113 |
-
}
|
114 |
-
|
115 |
-
const nexlSource = {
|
116 |
-
fileEncoding: confConsts.ENCODING_UTF8,
|
117 |
-
basePath: confMgmt.getNexlStorageDir(),
|
118 |
-
filePath: fullPath,
|
119 |
-
fileContent: req.body[diConsts.FILE_BODY]
|
120 |
-
};
|
121 |
-
|
122 |
-
// resolving metadata for [relativePath]
|
123 |
-
let md;
|
124 |
-
try {
|
125 |
-
md = nexlEngine.parseMD(nexlSource);
|
126 |
-
} catch (e) {
|
127 |
-
logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`);
|
128 |
-
security.sendError(res, 'Failed to parse a file');
|
129 |
-
return;
|
130 |
-
}
|
131 |
-
|
132 |
-
res.send({
|
133 |
-
md: md2Expressions(md)
|
134 |
-
});
|
135 |
-
});
|
136 |
-
|
137 |
-
//////////////////////////////////////////////////////////////////////////////
|
138 |
-
// reindex files
|
139 |
-
//////////////////////////////////////////////////////////////////////////////
|
140 |
-
router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) {
|
141 |
-
const username = security.getLoggedInUsername(req);
|
142 |
-
|
143 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`);
|
144 |
-
|
145 |
-
if (!security.isAdmin(username)) {
|
146 |
-
logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username);
|
147 |
-
security.sendError(res, 'admin permissions required');
|
148 |
-
return;
|
149 |
-
}
|
150 |
-
|
151 |
-
storageUtils.cacheStorageFiles()
|
152 |
-
.then(result => res.send({}))
|
153 |
-
.catch(err => {
|
154 |
-
logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`);
|
155 |
-
security.sendError(res, 'Failed to reindex');
|
156 |
-
});
|
157 |
-
});
|
158 |
-
|
159 |
-
//////////////////////////////////////////////////////////////////////////////
|
160 |
-
// find file
|
161 |
-
//////////////////////////////////////////////////////////////////////////////
|
162 |
-
router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) {
|
163 |
-
const username = security.getLoggedInUsername(req);
|
164 |
-
|
165 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
166 |
-
const text = req.body[di.TEXT];
|
167 |
-
const matchCase = req.body[di.MATCH_CASE];
|
168 |
-
const isRegex = req.body[di.IS_REGEX];
|
169 |
-
|
170 |
-
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}]`);
|
171 |
-
|
172 |
-
// todo : automate validations !!!
|
173 |
-
// todo : automate validations !!!
|
174 |
-
// todo : automate validations !!!
|
175 |
-
|
176 |
-
// validating relativePath
|
177 |
-
if (!j79.isString(relativePath) || relativePath.text < 1) {
|
178 |
-
logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
179 |
-
security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
180 |
-
return;
|
181 |
-
}
|
182 |
-
|
183 |
-
// validating text
|
184 |
-
if (!j79.isString(text) || text.length < 1) {
|
185 |
-
logger.log.error('Empty text is not allowed');
|
186 |
-
security.sendError(res, 'Empty text is not allowed');
|
187 |
-
return;
|
188 |
-
}
|
189 |
-
|
190 |
-
// validating matchCase
|
191 |
-
if (!j79.isBool(matchCase)) {
|
192 |
-
logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`);
|
193 |
-
security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`);
|
194 |
-
return;
|
195 |
-
}
|
196 |
-
|
197 |
-
// validating isRegex
|
198 |
-
if (!j79.isBool(matchCase)) {
|
199 |
-
logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`);
|
200 |
-
security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`);
|
201 |
-
return;
|
202 |
-
}
|
203 |
-
|
204 |
-
if (!security.hasReadPermission(username)) {
|
205 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username);
|
206 |
-
security.sendError(res, 'No read permissions');
|
207 |
-
return;
|
208 |
-
}
|
209 |
-
|
210 |
-
const data = {};
|
211 |
-
data[di.RELATIVE_PATH] = relativePath;
|
212 |
-
data[di.TEXT] = text;
|
213 |
-
data[di.MATCH_CASE] = matchCase;
|
214 |
-
data[di.IS_REGEX] = isRegex;
|
215 |
-
|
216 |
-
storageUtils.findInFiles(data).then(
|
217 |
-
result => res.send({result: result})
|
218 |
-
).catch(err => {
|
219 |
-
logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`);
|
220 |
-
security.sendError(res, 'Find in files failed');
|
221 |
-
});
|
222 |
-
});
|
223 |
-
|
224 |
-
//////////////////////////////////////////////////////////////////////////////
|
225 |
-
// move item
|
226 |
-
//////////////////////////////////////////////////////////////////////////////
|
227 |
-
router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) {
|
228 |
-
const username = security.getLoggedInUsername(req);
|
229 |
-
const source = req.body['source'];
|
230 |
-
const dest = req.body['dest'];
|
231 |
-
|
232 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`);
|
233 |
-
|
234 |
-
// validating ( must not empty string )
|
235 |
-
if (!j79.isString(source) || source.length < 1) {
|
236 |
-
logger.log.error('Invalid source item');
|
237 |
-
security.sendError(res, 'Invalid source item');
|
238 |
-
return;
|
239 |
-
}
|
240 |
-
|
241 |
-
// validating
|
242 |
-
if (!j79.isString(dest)) {
|
243 |
-
logger.log.error('Invalid dest item');
|
244 |
-
security.sendError(res, 'Invalid dest item');
|
245 |
-
return;
|
246 |
-
}
|
247 |
-
|
248 |
-
if (!security.hasWritePermission(username)) {
|
249 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to move items', username);
|
250 |
-
security.sendError(res, 'No write permissions');
|
251 |
-
return;
|
252 |
-
}
|
253 |
-
|
254 |
-
return storageUtils.move(source, dest)
|
255 |
-
.then(_ => {
|
256 |
-
res.send({});
|
257 |
-
logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`);
|
258 |
-
})
|
259 |
-
.catch(
|
260 |
-
(err) => {
|
261 |
-
logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err));
|
262 |
-
security.sendError(res, 'Failed to move item');
|
263 |
-
});
|
264 |
-
});
|
265 |
-
|
266 |
-
//////////////////////////////////////////////////////////////////////////////
|
267 |
-
// rename item
|
268 |
-
//////////////////////////////////////////////////////////////////////////////
|
269 |
-
router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) {
|
270 |
-
const username = security.getLoggedInUsername(req);
|
271 |
-
const relativePath = req.body['relativePath'];
|
272 |
-
const newRelativePath = req.body['newRelativePath'];
|
273 |
-
|
274 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`);
|
275 |
-
|
276 |
-
// validating ( must not empty string )
|
277 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
278 |
-
logger.log.error('Invalid relativePath');
|
279 |
-
security.sendError(res, 'Invalid relativePath');
|
280 |
-
return;
|
281 |
-
}
|
282 |
-
|
283 |
-
// validating ( must not empty string )
|
284 |
-
if (!j79.isString(newRelativePath) || newRelativePath.length < 1) {
|
285 |
-
logger.log.error('Invalid newRelativePath');
|
286 |
-
security.sendError(res, 'Invalid newRelativePath');
|
287 |
-
return;
|
288 |
-
}
|
289 |
-
|
290 |
-
if (!security.hasWritePermission(username)) {
|
291 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username);
|
292 |
-
security.sendError(res, 'No write permissions');
|
293 |
-
return;
|
294 |
-
}
|
295 |
-
|
296 |
-
return storageUtils.rename(relativePath, newRelativePath)
|
297 |
-
.then(_ => {
|
298 |
-
res.send({});
|
299 |
-
logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`);
|
300 |
-
})
|
301 |
-
.catch(
|
302 |
-
(err) => {
|
303 |
-
logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err));
|
304 |
-
security.sendError(res, 'Failed to rename item');
|
305 |
-
});
|
306 |
-
});
|
307 |
-
|
308 |
-
//////////////////////////////////////////////////////////////////////////////
|
309 |
-
// delete item
|
310 |
-
//////////////////////////////////////////////////////////////////////////////
|
311 |
-
router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) {
|
312 |
-
const username = security.getLoggedInUsername(req);
|
313 |
-
const relativePath = req.body['relativePath'];
|
314 |
-
|
315 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
316 |
-
|
317 |
-
// validating ( must not empty string )
|
318 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
319 |
-
logger.log.error('Invalid relativePath');
|
320 |
-
security.sendError(res, 'Invalid relativePath');
|
321 |
-
return;
|
322 |
-
}
|
323 |
-
|
324 |
-
if (!security.hasWritePermission(username)) {
|
325 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username);
|
326 |
-
security.sendError(res, 'No write permissions');
|
327 |
-
return;
|
328 |
-
}
|
329 |
-
|
330 |
-
return storageUtils.deleteItem(relativePath)
|
331 |
-
.then(_ => {
|
332 |
-
res.send({});
|
333 |
-
logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`);
|
334 |
-
})
|
335 |
-
.catch(
|
336 |
-
(err) => {
|
337 |
-
logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
338 |
-
security.sendError(res, 'Failed to delete item');
|
339 |
-
});
|
340 |
-
});
|
341 |
-
|
342 |
-
//////////////////////////////////////////////////////////////////////////////
|
343 |
-
// make-dir
|
344 |
-
//////////////////////////////////////////////////////////////////////////////
|
345 |
-
router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) {
|
346 |
-
const username = security.getLoggedInUsername(req);
|
347 |
-
const relativePath = req.body['relativePath'];
|
348 |
-
|
349 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
350 |
-
|
351 |
-
// validating ( must not empty string )
|
352 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
353 |
-
logger.log.error('Invalid relativePath');
|
354 |
-
security.sendError(res, 'Invalid relativePath');
|
355 |
-
return;
|
356 |
-
}
|
357 |
-
|
358 |
-
if (!security.hasWritePermission(username)) {
|
359 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username);
|
360 |
-
security.sendError(res, 'No write permissions');
|
361 |
-
return;
|
362 |
-
}
|
363 |
-
|
364 |
-
return storageUtils.mkdir(relativePath)
|
365 |
-
.then(_ => {
|
366 |
-
res.send({});
|
367 |
-
logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`);
|
368 |
-
})
|
369 |
-
.catch(
|
370 |
-
(err) => {
|
371 |
-
logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
372 |
-
security.sendError(res, 'Failed to create a directory');
|
373 |
-
});
|
374 |
-
});
|
375 |
-
|
376 |
-
//////////////////////////////////////////////////////////////////////////////
|
377 |
-
// get tree items hierarchy
|
378 |
-
//////////////////////////////////////////////////////////////////////////////
|
379 |
-
router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) {
|
380 |
-
const username = security.getLoggedInUsername(req);
|
381 |
-
|
382 |
-
logger.log.debug(`Getting tree items hierarchy by [${username}] user`);
|
383 |
-
|
384 |
-
if (!security.hasReadPermission(username)) {
|
385 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
386 |
-
security.sendError(res, 'No read permissions');
|
387 |
-
return;
|
388 |
-
}
|
389 |
-
|
390 |
-
res.send(storageUtils.getTreeItems());
|
391 |
-
});
|
392 |
-
|
393 |
-
//////////////////////////////////////////////////////////////////////////////
|
394 |
-
// list-dirs, list-files, list-files-and-dirs
|
395 |
-
//////////////////////////////////////////////////////////////////////////////
|
396 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) {
|
397 |
-
const username = security.getLoggedInUsername(req);
|
398 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
399 |
-
|
400 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
401 |
-
|
402 |
-
if (!security.hasReadPermission(username)) {
|
403 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
404 |
-
security.sendError(res, 'No read permissions');
|
405 |
-
return;
|
406 |
-
}
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
411 |
-
// res.send(storageUtils.listFiles(relativePath));
|
412 |
-
// FIXED:
|
413 |
-
|
414 |
-
});
|
415 |
-
|
416 |
-
router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) {
|
417 |
-
const username = security.getLoggedInUsername(req);
|
418 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
419 |
-
|
420 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
421 |
-
|
422 |
-
if (!security.hasReadPermission(username)) {
|
423 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
424 |
-
security.sendError(res, 'No read permissions');
|
425 |
-
return;
|
426 |
-
}
|
427 |
-
|
428 |
-
|
429 |
-
res.send(storageUtils.listDirs(relativePath));
|
430 |
-
});
|
431 |
-
|
432 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) {
|
433 |
-
const username = security.getLoggedInUsername(req);
|
434 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
435 |
-
|
436 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
437 |
-
|
438 |
-
if (!security.hasReadPermission(username)) {
|
439 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
440 |
-
security.sendError(res, 'No read permissions');
|
441 |
-
return;
|
442 |
-
}
|
443 |
-
|
444 |
-
|
445 |
-
res.send(storageUtils.listDirsAndFiles(relativePath));
|
446 |
-
});
|
447 |
-
|
448 |
-
//////////////////////////////////////////////////////////////////////////////
|
449 |
-
// load file from storage
|
450 |
-
//////////////////////////////////////////////////////////////////////////////
|
451 |
-
router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) {
|
452 |
-
const username = security.getLoggedInUsername(req);
|
453 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
454 |
-
|
455 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
456 |
-
|
457 |
-
if (!security.hasReadPermission(username)) {
|
458 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username);
|
459 |
-
security.sendError(res, 'No read permissions');
|
460 |
-
return;
|
461 |
-
}
|
462 |
-
|
463 |
-
const currentTime = new Date().getTime();
|
464 |
-
|
465 |
-
return storageUtils.loadFileFromStorage(relativePath)
|
466 |
-
.then(data => {
|
467 |
-
const body = {};
|
468 |
-
body[di.FILE_BODY] = data;
|
469 |
-
body[di.FILE_LOAD_TIME] = currentTime;
|
470 |
-
res.send(body);
|
471 |
-
logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`);
|
472 |
-
})
|
473 |
-
.catch(
|
474 |
-
(err) => {
|
475 |
-
logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
476 |
-
security.sendError(res, 'Failed to load file');
|
477 |
-
});
|
478 |
-
});
|
479 |
-
|
480 |
-
//////////////////////////////////////////////////////////////////////////////
|
481 |
-
// save file to storage
|
482 |
-
//////////////////////////////////////////////////////////////////////////////
|
483 |
-
router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) {
|
484 |
-
const username = security.getLoggedInUsername(req);
|
485 |
-
const relativePath = req.body['relativePath'];
|
486 |
-
const content = req.body['content'];
|
487 |
-
const fileLoadTime = req.body[di.FILE_LOAD_TIME];
|
488 |
-
|
489 |
-
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}]`);
|
490 |
-
|
491 |
-
// validating ( must not empty string )
|
492 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
493 |
-
logger.log.error('Invalid relativePath');
|
494 |
-
security.sendError(res, 'Invalid relativePath');
|
495 |
-
return;
|
496 |
-
}
|
497 |
-
|
498 |
-
if (!security.hasWritePermission(username)) {
|
499 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username);
|
500 |
-
security.sendError(res, 'No write permissions');
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
|
504 |
-
return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime)
|
505 |
-
.then(result => {
|
506 |
-
res.send(result);
|
507 |
-
logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`);
|
508 |
-
})
|
509 |
-
.catch(
|
510 |
-
(err) => {
|
511 |
-
logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
512 |
-
security.sendError(res, 'Failed to save file');
|
513 |
-
});
|
514 |
-
});
|
515 |
-
|
516 |
-
//////////////////////////////////////////////////////////////////////////////
|
517 |
-
// undeclared routes
|
518 |
-
//////////////////////////////////////////////////////////////////////////////
|
519 |
-
router.post('/*', function (req, res) {
|
520 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
521 |
-
security.sendError(res, `Unknown route`, 404);
|
522 |
-
});
|
523 |
-
|
524 |
-
router.get('/*', function (req, res) {
|
525 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
526 |
-
security.sendError(res, `Unknown route`, 404);
|
527 |
-
});
|
528 |
-
|
529 |
-
// --------------------------------------------------------------------------------
|
530 |
-
module.exports = router;
|
531 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/141.js
DELETED
@@ -1,531 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const path = require('path');
|
3 |
-
const j79 = require('j79-utils');
|
4 |
-
const nexlEngine = require('nexl-engine');
|
5 |
-
|
6 |
-
const storageUtils = require('../../api/storage-utils');
|
7 |
-
const security = require('../../api/security');
|
8 |
-
const utils = require('../../api/utils');
|
9 |
-
const logger = require('../../api/logger');
|
10 |
-
const restUtls = require('../../common/rest-urls');
|
11 |
-
const di = require('../../common/data-interchange-constants');
|
12 |
-
const confMgmt = require('../../api/conf-mgmt');
|
13 |
-
const confConsts = require('../../common/conf-constants');
|
14 |
-
const diConsts = require('../../common/data-interchange-constants');
|
15 |
-
|
16 |
-
const router = express.Router();
|
17 |
-
|
18 |
-
//////////////////////////////////////////////////////////////////////////////
|
19 |
-
// [/nexl/storage/set-var]
|
20 |
-
//////////////////////////////////////////////////////////////////////////////
|
21 |
-
router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) {
|
22 |
-
// checking for permissions
|
23 |
-
const username = security.getLoggedInUsername(req);
|
24 |
-
if (!security.hasWritePermission(username)) {
|
25 |
-
logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username);
|
26 |
-
security.sendError(res, 'No write permissions');
|
27 |
-
return;
|
28 |
-
}
|
29 |
-
|
30 |
-
// resolving params
|
31 |
-
const relativePath = req.body['relativePath'];
|
32 |
-
const varName = req.body['varName'];
|
33 |
-
const newValue = req.body['newValue'];
|
34 |
-
|
35 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`);
|
36 |
-
|
37 |
-
// validating relativePath
|
38 |
-
if (!relativePath) {
|
39 |
-
logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
40 |
-
security.sendError(res, 'The [relativePath] is not provided');
|
41 |
-
return;
|
42 |
-
}
|
43 |
-
|
44 |
-
// validating varName
|
45 |
-
if (!varName) {
|
46 |
-
logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
47 |
-
security.sendError(res, 'The [varName] is not provided');
|
48 |
-
return;
|
49 |
-
}
|
50 |
-
|
51 |
-
// validating newValue
|
52 |
-
if (!newValue) {
|
53 |
-
logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
54 |
-
security.sendError(res, 'The [newValue] is not provided');
|
55 |
-
return;
|
56 |
-
}
|
57 |
-
|
58 |
-
return storageUtils.setVar(relativePath, varName, newValue)
|
59 |
-
.then(_ => {
|
60 |
-
res.send({});
|
61 |
-
logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`);
|
62 |
-
})
|
63 |
-
.catch(
|
64 |
-
(err) => {
|
65 |
-
logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`);
|
66 |
-
security.sendError(res, 'Failed to update a JavaScript var');
|
67 |
-
});
|
68 |
-
});
|
69 |
-
|
70 |
-
|
71 |
-
//////////////////////////////////////////////////////////////////////////////
|
72 |
-
// md
|
73 |
-
//////////////////////////////////////////////////////////////////////////////
|
74 |
-
function md2Expressions(md) {
|
75 |
-
const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g');
|
76 |
-
const result = [];
|
77 |
-
md.forEach(item => {
|
78 |
-
if (item.type === 'Function') {
|
79 |
-
const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`;
|
80 |
-
result.push(`\${${args}${item.name}()}`);
|
81 |
-
return;
|
82 |
-
}
|
83 |
-
|
84 |
-
result.push(`\${${item.name}}`);
|
85 |
-
|
86 |
-
if (item.type === 'Object' && item.keys) {
|
87 |
-
item.keys.forEach(key => {
|
88 |
-
const keyEscaped = key.replace(opRegex, '\\$1');
|
89 |
-
result.push(`\${${item.name}.${keyEscaped}}`);
|
90 |
-
});
|
91 |
-
}
|
92 |
-
});
|
93 |
-
return result;
|
94 |
-
}
|
95 |
-
|
96 |
-
router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) {
|
97 |
-
const username = security.getLoggedInUsername(req);
|
98 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
99 |
-
|
100 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
101 |
-
|
102 |
-
if (!security.hasReadPermission(username)) {
|
103 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username);
|
104 |
-
security.sendError(res, 'No read permissions');
|
105 |
-
return;
|
106 |
-
}
|
107 |
-
|
108 |
-
const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);
|
109 |
-
if (!utils.isFilePathValid(fullPath)) {
|
110 |
-
logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`);
|
111 |
-
security.sendError(res, 'Unacceptable path');
|
112 |
-
return;
|
113 |
-
}
|
114 |
-
|
115 |
-
const nexlSource = {
|
116 |
-
fileEncoding: confConsts.ENCODING_UTF8,
|
117 |
-
basePath: confMgmt.getNexlStorageDir(),
|
118 |
-
filePath: fullPath,
|
119 |
-
fileContent: req.body[diConsts.FILE_BODY]
|
120 |
-
};
|
121 |
-
|
122 |
-
// resolving metadata for [relativePath]
|
123 |
-
let md;
|
124 |
-
try {
|
125 |
-
md = nexlEngine.parseMD(nexlSource);
|
126 |
-
} catch (e) {
|
127 |
-
logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`);
|
128 |
-
security.sendError(res, 'Failed to parse a file');
|
129 |
-
return;
|
130 |
-
}
|
131 |
-
|
132 |
-
res.send({
|
133 |
-
md: md2Expressions(md)
|
134 |
-
});
|
135 |
-
});
|
136 |
-
|
137 |
-
//////////////////////////////////////////////////////////////////////////////
|
138 |
-
// reindex files
|
139 |
-
//////////////////////////////////////////////////////////////////////////////
|
140 |
-
router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) {
|
141 |
-
const username = security.getLoggedInUsername(req);
|
142 |
-
|
143 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`);
|
144 |
-
|
145 |
-
if (!security.isAdmin(username)) {
|
146 |
-
logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username);
|
147 |
-
security.sendError(res, 'admin permissions required');
|
148 |
-
return;
|
149 |
-
}
|
150 |
-
|
151 |
-
storageUtils.cacheStorageFiles()
|
152 |
-
.then(result => res.send({}))
|
153 |
-
.catch(err => {
|
154 |
-
logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`);
|
155 |
-
security.sendError(res, 'Failed to reindex');
|
156 |
-
});
|
157 |
-
});
|
158 |
-
|
159 |
-
//////////////////////////////////////////////////////////////////////////////
|
160 |
-
// find file
|
161 |
-
//////////////////////////////////////////////////////////////////////////////
|
162 |
-
router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) {
|
163 |
-
const username = security.getLoggedInUsername(req);
|
164 |
-
|
165 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
166 |
-
const text = req.body[di.TEXT];
|
167 |
-
const matchCase = req.body[di.MATCH_CASE];
|
168 |
-
const isRegex = req.body[di.IS_REGEX];
|
169 |
-
|
170 |
-
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}]`);
|
171 |
-
|
172 |
-
// todo : automate validations !!!
|
173 |
-
// todo : automate validations !!!
|
174 |
-
// todo : automate validations !!!
|
175 |
-
|
176 |
-
// validating relativePath
|
177 |
-
if (!j79.isString(relativePath) || relativePath.text < 1) {
|
178 |
-
logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
179 |
-
security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
180 |
-
return;
|
181 |
-
}
|
182 |
-
|
183 |
-
// validating text
|
184 |
-
if (!j79.isString(text) || text.length < 1) {
|
185 |
-
logger.log.error('Empty text is not allowed');
|
186 |
-
security.sendError(res, 'Empty text is not allowed');
|
187 |
-
return;
|
188 |
-
}
|
189 |
-
|
190 |
-
// validating matchCase
|
191 |
-
if (!j79.isBool(matchCase)) {
|
192 |
-
logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`);
|
193 |
-
security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`);
|
194 |
-
return;
|
195 |
-
}
|
196 |
-
|
197 |
-
// validating isRegex
|
198 |
-
if (!j79.isBool(matchCase)) {
|
199 |
-
logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`);
|
200 |
-
security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`);
|
201 |
-
return;
|
202 |
-
}
|
203 |
-
|
204 |
-
if (!security.hasReadPermission(username)) {
|
205 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username);
|
206 |
-
security.sendError(res, 'No read permissions');
|
207 |
-
return;
|
208 |
-
}
|
209 |
-
|
210 |
-
const data = {};
|
211 |
-
data[di.RELATIVE_PATH] = relativePath;
|
212 |
-
data[di.TEXT] = text;
|
213 |
-
data[di.MATCH_CASE] = matchCase;
|
214 |
-
data[di.IS_REGEX] = isRegex;
|
215 |
-
|
216 |
-
storageUtils.findInFiles(data).then(
|
217 |
-
result => res.send({result: result})
|
218 |
-
).catch(err => {
|
219 |
-
logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`);
|
220 |
-
security.sendError(res, 'Find in files failed');
|
221 |
-
});
|
222 |
-
});
|
223 |
-
|
224 |
-
//////////////////////////////////////////////////////////////////////////////
|
225 |
-
// move item
|
226 |
-
//////////////////////////////////////////////////////////////////////////////
|
227 |
-
router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) {
|
228 |
-
const username = security.getLoggedInUsername(req);
|
229 |
-
const source = req.body['source'];
|
230 |
-
const dest = req.body['dest'];
|
231 |
-
|
232 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`);
|
233 |
-
|
234 |
-
// validating ( must not empty string )
|
235 |
-
if (!j79.isString(source) || source.length < 1) {
|
236 |
-
logger.log.error('Invalid source item');
|
237 |
-
security.sendError(res, 'Invalid source item');
|
238 |
-
return;
|
239 |
-
}
|
240 |
-
|
241 |
-
// validating
|
242 |
-
if (!j79.isString(dest)) {
|
243 |
-
logger.log.error('Invalid dest item');
|
244 |
-
security.sendError(res, 'Invalid dest item');
|
245 |
-
return;
|
246 |
-
}
|
247 |
-
|
248 |
-
if (!security.hasWritePermission(username)) {
|
249 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to move items', username);
|
250 |
-
security.sendError(res, 'No write permissions');
|
251 |
-
return;
|
252 |
-
}
|
253 |
-
|
254 |
-
return storageUtils.move(source, dest)
|
255 |
-
.then(_ => {
|
256 |
-
res.send({});
|
257 |
-
logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`);
|
258 |
-
})
|
259 |
-
.catch(
|
260 |
-
(err) => {
|
261 |
-
logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err));
|
262 |
-
security.sendError(res, 'Failed to move item');
|
263 |
-
});
|
264 |
-
});
|
265 |
-
|
266 |
-
//////////////////////////////////////////////////////////////////////////////
|
267 |
-
// rename item
|
268 |
-
//////////////////////////////////////////////////////////////////////////////
|
269 |
-
router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) {
|
270 |
-
const username = security.getLoggedInUsername(req);
|
271 |
-
const relativePath = req.body['relativePath'];
|
272 |
-
const newRelativePath = req.body['newRelativePath'];
|
273 |
-
|
274 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`);
|
275 |
-
|
276 |
-
// validating ( must not empty string )
|
277 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
278 |
-
logger.log.error('Invalid relativePath');
|
279 |
-
security.sendError(res, 'Invalid relativePath');
|
280 |
-
return;
|
281 |
-
}
|
282 |
-
|
283 |
-
// validating ( must not empty string )
|
284 |
-
if (!j79.isString(newRelativePath) || newRelativePath.length < 1) {
|
285 |
-
logger.log.error('Invalid newRelativePath');
|
286 |
-
security.sendError(res, 'Invalid newRelativePath');
|
287 |
-
return;
|
288 |
-
}
|
289 |
-
|
290 |
-
if (!security.hasWritePermission(username)) {
|
291 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username);
|
292 |
-
security.sendError(res, 'No write permissions');
|
293 |
-
return;
|
294 |
-
}
|
295 |
-
|
296 |
-
return storageUtils.rename(relativePath, newRelativePath)
|
297 |
-
.then(_ => {
|
298 |
-
res.send({});
|
299 |
-
logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`);
|
300 |
-
})
|
301 |
-
.catch(
|
302 |
-
(err) => {
|
303 |
-
logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err));
|
304 |
-
security.sendError(res, 'Failed to rename item');
|
305 |
-
});
|
306 |
-
});
|
307 |
-
|
308 |
-
//////////////////////////////////////////////////////////////////////////////
|
309 |
-
// delete item
|
310 |
-
//////////////////////////////////////////////////////////////////////////////
|
311 |
-
router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) {
|
312 |
-
const username = security.getLoggedInUsername(req);
|
313 |
-
const relativePath = req.body['relativePath'];
|
314 |
-
|
315 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
316 |
-
|
317 |
-
// validating ( must not empty string )
|
318 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
319 |
-
logger.log.error('Invalid relativePath');
|
320 |
-
security.sendError(res, 'Invalid relativePath');
|
321 |
-
return;
|
322 |
-
}
|
323 |
-
|
324 |
-
if (!security.hasWritePermission(username)) {
|
325 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username);
|
326 |
-
security.sendError(res, 'No write permissions');
|
327 |
-
return;
|
328 |
-
}
|
329 |
-
|
330 |
-
return storageUtils.deleteItem(relativePath)
|
331 |
-
.then(_ => {
|
332 |
-
res.send({});
|
333 |
-
logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`);
|
334 |
-
})
|
335 |
-
.catch(
|
336 |
-
(err) => {
|
337 |
-
logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
338 |
-
security.sendError(res, 'Failed to delete item');
|
339 |
-
});
|
340 |
-
});
|
341 |
-
|
342 |
-
//////////////////////////////////////////////////////////////////////////////
|
343 |
-
// make-dir
|
344 |
-
//////////////////////////////////////////////////////////////////////////////
|
345 |
-
router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) {
|
346 |
-
const username = security.getLoggedInUsername(req);
|
347 |
-
const relativePath = req.body['relativePath'];
|
348 |
-
|
349 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
350 |
-
|
351 |
-
// validating ( must not empty string )
|
352 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
353 |
-
logger.log.error('Invalid relativePath');
|
354 |
-
security.sendError(res, 'Invalid relativePath');
|
355 |
-
return;
|
356 |
-
}
|
357 |
-
|
358 |
-
if (!security.hasWritePermission(username)) {
|
359 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username);
|
360 |
-
security.sendError(res, 'No write permissions');
|
361 |
-
return;
|
362 |
-
}
|
363 |
-
|
364 |
-
return storageUtils.mkdir(relativePath)
|
365 |
-
.then(_ => {
|
366 |
-
res.send({});
|
367 |
-
logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`);
|
368 |
-
})
|
369 |
-
.catch(
|
370 |
-
(err) => {
|
371 |
-
logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
372 |
-
security.sendError(res, 'Failed to create a directory');
|
373 |
-
});
|
374 |
-
});
|
375 |
-
|
376 |
-
//////////////////////////////////////////////////////////////////////////////
|
377 |
-
// get tree items hierarchy
|
378 |
-
//////////////////////////////////////////////////////////////////////////////
|
379 |
-
router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) {
|
380 |
-
const username = security.getLoggedInUsername(req);
|
381 |
-
|
382 |
-
logger.log.debug(`Getting tree items hierarchy by [${username}] user`);
|
383 |
-
|
384 |
-
if (!security.hasReadPermission(username)) {
|
385 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
386 |
-
security.sendError(res, 'No read permissions');
|
387 |
-
return;
|
388 |
-
}
|
389 |
-
|
390 |
-
res.send(storageUtils.getTreeItems());
|
391 |
-
});
|
392 |
-
|
393 |
-
//////////////////////////////////////////////////////////////////////////////
|
394 |
-
// list-dirs, list-files, list-files-and-dirs
|
395 |
-
//////////////////////////////////////////////////////////////////////////////
|
396 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) {
|
397 |
-
const username = security.getLoggedInUsername(req);
|
398 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
399 |
-
|
400 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
401 |
-
|
402 |
-
if (!security.hasReadPermission(username)) {
|
403 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
404 |
-
security.sendError(res, 'No read permissions');
|
405 |
-
return;
|
406 |
-
}
|
407 |
-
|
408 |
-
|
409 |
-
res.send(storageUtils.listFiles(relativePath));
|
410 |
-
});
|
411 |
-
|
412 |
-
router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) {
|
413 |
-
const username = security.getLoggedInUsername(req);
|
414 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
415 |
-
|
416 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
417 |
-
|
418 |
-
if (!security.hasReadPermission(username)) {
|
419 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
420 |
-
security.sendError(res, 'No read permissions');
|
421 |
-
return;
|
422 |
-
}
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
427 |
-
// res.send(storageUtils.listDirs(relativePath));
|
428 |
-
// FIXED:
|
429 |
-
|
430 |
-
});
|
431 |
-
|
432 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) {
|
433 |
-
const username = security.getLoggedInUsername(req);
|
434 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
435 |
-
|
436 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
437 |
-
|
438 |
-
if (!security.hasReadPermission(username)) {
|
439 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
440 |
-
security.sendError(res, 'No read permissions');
|
441 |
-
return;
|
442 |
-
}
|
443 |
-
|
444 |
-
|
445 |
-
res.send(storageUtils.listDirsAndFiles(relativePath));
|
446 |
-
});
|
447 |
-
|
448 |
-
//////////////////////////////////////////////////////////////////////////////
|
449 |
-
// load file from storage
|
450 |
-
//////////////////////////////////////////////////////////////////////////////
|
451 |
-
router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) {
|
452 |
-
const username = security.getLoggedInUsername(req);
|
453 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
454 |
-
|
455 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
456 |
-
|
457 |
-
if (!security.hasReadPermission(username)) {
|
458 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username);
|
459 |
-
security.sendError(res, 'No read permissions');
|
460 |
-
return;
|
461 |
-
}
|
462 |
-
|
463 |
-
const currentTime = new Date().getTime();
|
464 |
-
|
465 |
-
return storageUtils.loadFileFromStorage(relativePath)
|
466 |
-
.then(data => {
|
467 |
-
const body = {};
|
468 |
-
body[di.FILE_BODY] = data;
|
469 |
-
body[di.FILE_LOAD_TIME] = currentTime;
|
470 |
-
res.send(body);
|
471 |
-
logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`);
|
472 |
-
})
|
473 |
-
.catch(
|
474 |
-
(err) => {
|
475 |
-
logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
476 |
-
security.sendError(res, 'Failed to load file');
|
477 |
-
});
|
478 |
-
});
|
479 |
-
|
480 |
-
//////////////////////////////////////////////////////////////////////////////
|
481 |
-
// save file to storage
|
482 |
-
//////////////////////////////////////////////////////////////////////////////
|
483 |
-
router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) {
|
484 |
-
const username = security.getLoggedInUsername(req);
|
485 |
-
const relativePath = req.body['relativePath'];
|
486 |
-
const content = req.body['content'];
|
487 |
-
const fileLoadTime = req.body[di.FILE_LOAD_TIME];
|
488 |
-
|
489 |
-
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}]`);
|
490 |
-
|
491 |
-
// validating ( must not empty string )
|
492 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
493 |
-
logger.log.error('Invalid relativePath');
|
494 |
-
security.sendError(res, 'Invalid relativePath');
|
495 |
-
return;
|
496 |
-
}
|
497 |
-
|
498 |
-
if (!security.hasWritePermission(username)) {
|
499 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username);
|
500 |
-
security.sendError(res, 'No write permissions');
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
|
504 |
-
return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime)
|
505 |
-
.then(result => {
|
506 |
-
res.send(result);
|
507 |
-
logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`);
|
508 |
-
})
|
509 |
-
.catch(
|
510 |
-
(err) => {
|
511 |
-
logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
512 |
-
security.sendError(res, 'Failed to save file');
|
513 |
-
});
|
514 |
-
});
|
515 |
-
|
516 |
-
//////////////////////////////////////////////////////////////////////////////
|
517 |
-
// undeclared routes
|
518 |
-
//////////////////////////////////////////////////////////////////////////////
|
519 |
-
router.post('/*', function (req, res) {
|
520 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
521 |
-
security.sendError(res, `Unknown route`, 404);
|
522 |
-
});
|
523 |
-
|
524 |
-
router.get('/*', function (req, res) {
|
525 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
526 |
-
security.sendError(res, `Unknown route`, 404);
|
527 |
-
});
|
528 |
-
|
529 |
-
// --------------------------------------------------------------------------------
|
530 |
-
module.exports = router;
|
531 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/javaScript/142.js
DELETED
@@ -1,531 +0,0 @@
|
|
1 |
-
const express = require('express');
|
2 |
-
const path = require('path');
|
3 |
-
const j79 = require('j79-utils');
|
4 |
-
const nexlEngine = require('nexl-engine');
|
5 |
-
|
6 |
-
const storageUtils = require('../../api/storage-utils');
|
7 |
-
const security = require('../../api/security');
|
8 |
-
const utils = require('../../api/utils');
|
9 |
-
const logger = require('../../api/logger');
|
10 |
-
const restUtls = require('../../common/rest-urls');
|
11 |
-
const di = require('../../common/data-interchange-constants');
|
12 |
-
const confMgmt = require('../../api/conf-mgmt');
|
13 |
-
const confConsts = require('../../common/conf-constants');
|
14 |
-
const diConsts = require('../../common/data-interchange-constants');
|
15 |
-
|
16 |
-
const router = express.Router();
|
17 |
-
|
18 |
-
//////////////////////////////////////////////////////////////////////////////
|
19 |
-
// [/nexl/storage/set-var]
|
20 |
-
//////////////////////////////////////////////////////////////////////////////
|
21 |
-
router.post(restUtls.STORAGE.URLS.SET_VAR, function (req, res) {
|
22 |
-
// checking for permissions
|
23 |
-
const username = security.getLoggedInUsername(req);
|
24 |
-
if (!security.hasWritePermission(username)) {
|
25 |
-
logger.log.error('The [%s] user doesn\'t have write permission to update JavaScript files', username);
|
26 |
-
security.sendError(res, 'No write permissions');
|
27 |
-
return;
|
28 |
-
}
|
29 |
-
|
30 |
-
// resolving params
|
31 |
-
const relativePath = req.body['relativePath'];
|
32 |
-
const varName = req.body['varName'];
|
33 |
-
const newValue = req.body['newValue'];
|
34 |
-
|
35 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.SET_VAR}] request from the [${username}] user for [relativePath=${relativePath}] and [varName=${varName}]`);
|
36 |
-
|
37 |
-
// validating relativePath
|
38 |
-
if (!relativePath) {
|
39 |
-
logger.log.error(`The [relativePath] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
40 |
-
security.sendError(res, 'The [relativePath] is not provided');
|
41 |
-
return;
|
42 |
-
}
|
43 |
-
|
44 |
-
// validating varName
|
45 |
-
if (!varName) {
|
46 |
-
logger.log.error(`The [varName] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
47 |
-
security.sendError(res, 'The [varName] is not provided');
|
48 |
-
return;
|
49 |
-
}
|
50 |
-
|
51 |
-
// validating newValue
|
52 |
-
if (!newValue) {
|
53 |
-
logger.log.error(`The [newValue] is not provided for [${restUtls.STORAGE.URLS.SET_VAR}] URL. Requested by [${username}]`);
|
54 |
-
security.sendError(res, 'The [newValue] is not provided');
|
55 |
-
return;
|
56 |
-
}
|
57 |
-
|
58 |
-
return storageUtils.setVar(relativePath, varName, newValue)
|
59 |
-
.then(_ => {
|
60 |
-
res.send({});
|
61 |
-
logger.log.debug(`Updated a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]`);
|
62 |
-
})
|
63 |
-
.catch(
|
64 |
-
(err) => {
|
65 |
-
logger.log.error(`Failed to update a [varName=${varName}] in the [relativePath=${relativePath}] JavaScript file by [username=${username}]. Reason: [${ utils.formatErr(err)}]`);
|
66 |
-
security.sendError(res, 'Failed to update a JavaScript var');
|
67 |
-
});
|
68 |
-
});
|
69 |
-
|
70 |
-
|
71 |
-
//////////////////////////////////////////////////////////////////////////////
|
72 |
-
// md
|
73 |
-
//////////////////////////////////////////////////////////////////////////////
|
74 |
-
function md2Expressions(md) {
|
75 |
-
const opRegex = new RegExp(`([${nexlEngine.OPERATIONS_ESCAPED}])`, 'g');
|
76 |
-
const result = [];
|
77 |
-
md.forEach(item => {
|
78 |
-
if (item.type === 'Function') {
|
79 |
-
const args = item.args.length < 1 ? '' : `${item.args.join('|')}|`;
|
80 |
-
result.push(`\${${args}${item.name}()}`);
|
81 |
-
return;
|
82 |
-
}
|
83 |
-
|
84 |
-
result.push(`\${${item.name}}`);
|
85 |
-
|
86 |
-
if (item.type === 'Object' && item.keys) {
|
87 |
-
item.keys.forEach(key => {
|
88 |
-
const keyEscaped = key.replace(opRegex, '\\$1');
|
89 |
-
result.push(`\${${item.name}.${keyEscaped}}`);
|
90 |
-
});
|
91 |
-
}
|
92 |
-
});
|
93 |
-
return result;
|
94 |
-
}
|
95 |
-
|
96 |
-
router.post(restUtls.STORAGE.URLS.METADATA, function (req, res) {
|
97 |
-
const username = security.getLoggedInUsername(req);
|
98 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
99 |
-
|
100 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.METADATA}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
101 |
-
|
102 |
-
if (!security.hasReadPermission(username)) {
|
103 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load metadata', username);
|
104 |
-
security.sendError(res, 'No read permissions');
|
105 |
-
return;
|
106 |
-
}
|
107 |
-
|
108 |
-
const fullPath = path.join(confMgmt.getNexlStorageDir(), relativePath);
|
109 |
-
if (!utils.isFilePathValid(fullPath)) {
|
110 |
-
logger.log.error(`The [relativePath=${relativePath}] is unacceptable, requested by [user=${username}]`);
|
111 |
-
security.sendError(res, 'Unacceptable path');
|
112 |
-
return;
|
113 |
-
}
|
114 |
-
|
115 |
-
const nexlSource = {
|
116 |
-
fileEncoding: confConsts.ENCODING_UTF8,
|
117 |
-
basePath: confMgmt.getNexlStorageDir(),
|
118 |
-
filePath: fullPath,
|
119 |
-
fileContent: req.body[diConsts.FILE_BODY]
|
120 |
-
};
|
121 |
-
|
122 |
-
// resolving metadata for [relativePath]
|
123 |
-
let md;
|
124 |
-
try {
|
125 |
-
md = nexlEngine.parseMD(nexlSource);
|
126 |
-
} catch (e) {
|
127 |
-
logger.log.error(`Failed to parse a [relativePath=${relativePath}] file. Requested by [user=${username}]. [reason=${utils.formatErr(e)}]`);
|
128 |
-
security.sendError(res, 'Failed to parse a file');
|
129 |
-
return;
|
130 |
-
}
|
131 |
-
|
132 |
-
res.send({
|
133 |
-
md: md2Expressions(md)
|
134 |
-
});
|
135 |
-
});
|
136 |
-
|
137 |
-
//////////////////////////////////////////////////////////////////////////////
|
138 |
-
// reindex files
|
139 |
-
//////////////////////////////////////////////////////////////////////////////
|
140 |
-
router.post(restUtls.STORAGE.URLS.REINDEX_FILES, function (req, res) {
|
141 |
-
const username = security.getLoggedInUsername(req);
|
142 |
-
|
143 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.REINDEX_FILES}] request`);
|
144 |
-
|
145 |
-
if (!security.isAdmin(username)) {
|
146 |
-
logger.log.error('Cannot reindex file because the [%s] user doesn\'t have admin permissions', username);
|
147 |
-
security.sendError(res, 'admin permissions required');
|
148 |
-
return;
|
149 |
-
}
|
150 |
-
|
151 |
-
storageUtils.cacheStorageFiles()
|
152 |
-
.then(result => res.send({}))
|
153 |
-
.catch(err => {
|
154 |
-
logger.log.error(`Failed to reindex files. Reason: [${utils.formatErr(err)}]`);
|
155 |
-
security.sendError(res, 'Failed to reindex');
|
156 |
-
});
|
157 |
-
});
|
158 |
-
|
159 |
-
//////////////////////////////////////////////////////////////////////////////
|
160 |
-
// find file
|
161 |
-
//////////////////////////////////////////////////////////////////////////////
|
162 |
-
router.post(restUtls.STORAGE.URLS.FILE_IN_FILES, function (req, res) {
|
163 |
-
const username = security.getLoggedInUsername(req);
|
164 |
-
|
165 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
166 |
-
const text = req.body[di.TEXT];
|
167 |
-
const matchCase = req.body[di.MATCH_CASE];
|
168 |
-
const isRegex = req.body[di.IS_REGEX];
|
169 |
-
|
170 |
-
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}]`);
|
171 |
-
|
172 |
-
// todo : automate validations !!!
|
173 |
-
// todo : automate validations !!!
|
174 |
-
// todo : automate validations !!!
|
175 |
-
|
176 |
-
// validating relativePath
|
177 |
-
if (!j79.isString(relativePath) || relativePath.text < 1) {
|
178 |
-
logger.log.error(`The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
179 |
-
security.sendError(res, `The [${di.RELATIVE_PATH}] must be a valid non empty string`);
|
180 |
-
return;
|
181 |
-
}
|
182 |
-
|
183 |
-
// validating text
|
184 |
-
if (!j79.isString(text) || text.length < 1) {
|
185 |
-
logger.log.error('Empty text is not allowed');
|
186 |
-
security.sendError(res, 'Empty text is not allowed');
|
187 |
-
return;
|
188 |
-
}
|
189 |
-
|
190 |
-
// validating matchCase
|
191 |
-
if (!j79.isBool(matchCase)) {
|
192 |
-
logger.log.error(`The [${di.MATCH_CASE}] must be of a boolean type`);
|
193 |
-
security.sendError(res, `The [${di.MATCH_CASE}] must be of a boolean type`);
|
194 |
-
return;
|
195 |
-
}
|
196 |
-
|
197 |
-
// validating isRegex
|
198 |
-
if (!j79.isBool(matchCase)) {
|
199 |
-
logger.log.error(`The [${di.IS_REGEX}] must be of a boolean type`);
|
200 |
-
security.sendError(res, `The [${di.IS_REGEX}] must be of a boolean type`);
|
201 |
-
return;
|
202 |
-
}
|
203 |
-
|
204 |
-
if (!security.hasReadPermission(username)) {
|
205 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to search text in files', username);
|
206 |
-
security.sendError(res, 'No read permissions');
|
207 |
-
return;
|
208 |
-
}
|
209 |
-
|
210 |
-
const data = {};
|
211 |
-
data[di.RELATIVE_PATH] = relativePath;
|
212 |
-
data[di.TEXT] = text;
|
213 |
-
data[di.MATCH_CASE] = matchCase;
|
214 |
-
data[di.IS_REGEX] = isRegex;
|
215 |
-
|
216 |
-
storageUtils.findInFiles(data).then(
|
217 |
-
result => res.send({result: result})
|
218 |
-
).catch(err => {
|
219 |
-
logger.log.error(`Find in files failed. Reason: [${utils.formatErr(err)}]`);
|
220 |
-
security.sendError(res, 'Find in files failed');
|
221 |
-
});
|
222 |
-
});
|
223 |
-
|
224 |
-
//////////////////////////////////////////////////////////////////////////////
|
225 |
-
// move item
|
226 |
-
//////////////////////////////////////////////////////////////////////////////
|
227 |
-
router.post(restUtls.STORAGE.URLS.MOVE, function (req, res) {
|
228 |
-
const username = security.getLoggedInUsername(req);
|
229 |
-
const source = req.body['source'];
|
230 |
-
const dest = req.body['dest'];
|
231 |
-
|
232 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MOVE}] request from the [${username}] user for [source=${source}] [dest=${dest}]`);
|
233 |
-
|
234 |
-
// validating ( must not empty string )
|
235 |
-
if (!j79.isString(source) || source.length < 1) {
|
236 |
-
logger.log.error('Invalid source item');
|
237 |
-
security.sendError(res, 'Invalid source item');
|
238 |
-
return;
|
239 |
-
}
|
240 |
-
|
241 |
-
// validating
|
242 |
-
if (!j79.isString(dest)) {
|
243 |
-
logger.log.error('Invalid dest item');
|
244 |
-
security.sendError(res, 'Invalid dest item');
|
245 |
-
return;
|
246 |
-
}
|
247 |
-
|
248 |
-
if (!security.hasWritePermission(username)) {
|
249 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to move items', username);
|
250 |
-
security.sendError(res, 'No write permissions');
|
251 |
-
return;
|
252 |
-
}
|
253 |
-
|
254 |
-
return storageUtils.move(source, dest)
|
255 |
-
.then(_ => {
|
256 |
-
res.send({});
|
257 |
-
logger.log.log('verbose', `Moved a [${source}] item to [${dest}] by [${username}] user`);
|
258 |
-
})
|
259 |
-
.catch(
|
260 |
-
(err) => {
|
261 |
-
logger.log.error('Failed to move a [%s] file to [%s] for [%s] user. Reason : [%s]', source, dest, username, utils.formatErr(err));
|
262 |
-
security.sendError(res, 'Failed to move item');
|
263 |
-
});
|
264 |
-
});
|
265 |
-
|
266 |
-
//////////////////////////////////////////////////////////////////////////////
|
267 |
-
// rename item
|
268 |
-
//////////////////////////////////////////////////////////////////////////////
|
269 |
-
router.post(restUtls.STORAGE.URLS.RENAME, function (req, res) {
|
270 |
-
const username = security.getLoggedInUsername(req);
|
271 |
-
const relativePath = req.body['relativePath'];
|
272 |
-
const newRelativePath = req.body['newRelativePath'];
|
273 |
-
|
274 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.RENAME}] request from the [${username}] user for [relativePath=${relativePath}] [newRelativePath=${newRelativePath}]`);
|
275 |
-
|
276 |
-
// validating ( must not empty string )
|
277 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
278 |
-
logger.log.error('Invalid relativePath');
|
279 |
-
security.sendError(res, 'Invalid relativePath');
|
280 |
-
return;
|
281 |
-
}
|
282 |
-
|
283 |
-
// validating ( must not empty string )
|
284 |
-
if (!j79.isString(newRelativePath) || newRelativePath.length < 1) {
|
285 |
-
logger.log.error('Invalid newRelativePath');
|
286 |
-
security.sendError(res, 'Invalid newRelativePath');
|
287 |
-
return;
|
288 |
-
}
|
289 |
-
|
290 |
-
if (!security.hasWritePermission(username)) {
|
291 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to rename items', username);
|
292 |
-
security.sendError(res, 'No write permissions');
|
293 |
-
return;
|
294 |
-
}
|
295 |
-
|
296 |
-
return storageUtils.rename(relativePath, newRelativePath)
|
297 |
-
.then(_ => {
|
298 |
-
res.send({});
|
299 |
-
logger.log.log('verbose', `Renamed a [${relativePath}] item to [${newRelativePath}] by [${username}] user`);
|
300 |
-
})
|
301 |
-
.catch(
|
302 |
-
(err) => {
|
303 |
-
logger.log.error('Failed to rename a [%s] file to [%s] for [%s] user. Reason : [%s]', relativePath, newRelativePath, username, utils.formatErr(err));
|
304 |
-
security.sendError(res, 'Failed to rename item');
|
305 |
-
});
|
306 |
-
});
|
307 |
-
|
308 |
-
//////////////////////////////////////////////////////////////////////////////
|
309 |
-
// delete item
|
310 |
-
//////////////////////////////////////////////////////////////////////////////
|
311 |
-
router.post(restUtls.STORAGE.URLS.DELETE, function (req, res) {
|
312 |
-
const username = security.getLoggedInUsername(req);
|
313 |
-
const relativePath = req.body['relativePath'];
|
314 |
-
|
315 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.DELETE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
316 |
-
|
317 |
-
// validating ( must not empty string )
|
318 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
319 |
-
logger.log.error('Invalid relativePath');
|
320 |
-
security.sendError(res, 'Invalid relativePath');
|
321 |
-
return;
|
322 |
-
}
|
323 |
-
|
324 |
-
if (!security.hasWritePermission(username)) {
|
325 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to delete items', username);
|
326 |
-
security.sendError(res, 'No write permissions');
|
327 |
-
return;
|
328 |
-
}
|
329 |
-
|
330 |
-
return storageUtils.deleteItem(relativePath)
|
331 |
-
.then(_ => {
|
332 |
-
res.send({});
|
333 |
-
logger.log.log('verbose', `Deleted a [${relativePath}] item by [${username}] user`);
|
334 |
-
})
|
335 |
-
.catch(
|
336 |
-
(err) => {
|
337 |
-
logger.log.error('Failed to delete a [%s] item for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
338 |
-
security.sendError(res, 'Failed to delete item');
|
339 |
-
});
|
340 |
-
});
|
341 |
-
|
342 |
-
//////////////////////////////////////////////////////////////////////////////
|
343 |
-
// make-dir
|
344 |
-
//////////////////////////////////////////////////////////////////////////////
|
345 |
-
router.post(restUtls.STORAGE.URLS.MAKE_DIR, function (req, res, next) {
|
346 |
-
const username = security.getLoggedInUsername(req);
|
347 |
-
const relativePath = req.body['relativePath'];
|
348 |
-
|
349 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.MAKE_DIR}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
350 |
-
|
351 |
-
// validating ( must not empty string )
|
352 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
353 |
-
logger.log.error('Invalid relativePath');
|
354 |
-
security.sendError(res, 'Invalid relativePath');
|
355 |
-
return;
|
356 |
-
}
|
357 |
-
|
358 |
-
if (!security.hasWritePermission(username)) {
|
359 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to create new directory', username);
|
360 |
-
security.sendError(res, 'No write permissions');
|
361 |
-
return;
|
362 |
-
}
|
363 |
-
|
364 |
-
return storageUtils.mkdir(relativePath)
|
365 |
-
.then(_ => {
|
366 |
-
res.send({});
|
367 |
-
logger.log.log('verbose', `Created a [${relativePath}] directory by [${username}] user`);
|
368 |
-
})
|
369 |
-
.catch(
|
370 |
-
(err) => {
|
371 |
-
logger.log.error('Failed to create a [%s] directory for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
372 |
-
security.sendError(res, 'Failed to create a directory');
|
373 |
-
});
|
374 |
-
});
|
375 |
-
|
376 |
-
//////////////////////////////////////////////////////////////////////////////
|
377 |
-
// get tree items hierarchy
|
378 |
-
//////////////////////////////////////////////////////////////////////////////
|
379 |
-
router.post(restUtls.STORAGE.URLS.TREE_ITEMS, function (req, res, next) {
|
380 |
-
const username = security.getLoggedInUsername(req);
|
381 |
-
|
382 |
-
logger.log.debug(`Getting tree items hierarchy by [${username}] user`);
|
383 |
-
|
384 |
-
if (!security.hasReadPermission(username)) {
|
385 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
386 |
-
security.sendError(res, 'No read permissions');
|
387 |
-
return;
|
388 |
-
}
|
389 |
-
|
390 |
-
res.send(storageUtils.getTreeItems());
|
391 |
-
});
|
392 |
-
|
393 |
-
//////////////////////////////////////////////////////////////////////////////
|
394 |
-
// list-dirs, list-files, list-files-and-dirs
|
395 |
-
//////////////////////////////////////////////////////////////////////////////
|
396 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES, function (req, res, next) {
|
397 |
-
const username = security.getLoggedInUsername(req);
|
398 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
399 |
-
|
400 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
401 |
-
|
402 |
-
if (!security.hasReadPermission(username)) {
|
403 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
404 |
-
security.sendError(res, 'No read permissions');
|
405 |
-
return;
|
406 |
-
}
|
407 |
-
|
408 |
-
|
409 |
-
res.send(storageUtils.listFiles(relativePath));
|
410 |
-
});
|
411 |
-
|
412 |
-
router.post(restUtls.STORAGE.URLS.LIST_DIRS, function (req, res, next) {
|
413 |
-
const username = security.getLoggedInUsername(req);
|
414 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
415 |
-
|
416 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
417 |
-
|
418 |
-
if (!security.hasReadPermission(username)) {
|
419 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
420 |
-
security.sendError(res, 'No read permissions');
|
421 |
-
return;
|
422 |
-
}
|
423 |
-
|
424 |
-
|
425 |
-
res.send(storageUtils.listDirs(relativePath));
|
426 |
-
});
|
427 |
-
|
428 |
-
router.post(restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS, function (req, res, next) {
|
429 |
-
const username = security.getLoggedInUsername(req);
|
430 |
-
const relativePath = req.body[di.RELATIVE_PATH];
|
431 |
-
|
432 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LIST_FILES_AND_DIRS}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
433 |
-
|
434 |
-
if (!security.hasReadPermission(username)) {
|
435 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to get tree items hierarchy', username);
|
436 |
-
security.sendError(res, 'No read permissions');
|
437 |
-
return;
|
438 |
-
}
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
443 |
-
// res.send(storageUtils.listDirsAndFiles(relativePath));
|
444 |
-
// FIXED:
|
445 |
-
|
446 |
-
});
|
447 |
-
|
448 |
-
//////////////////////////////////////////////////////////////////////////////
|
449 |
-
// load file from storage
|
450 |
-
//////////////////////////////////////////////////////////////////////////////
|
451 |
-
router.post(restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE, function (req, res, next) {
|
452 |
-
const username = security.getLoggedInUsername(req);
|
453 |
-
const relativePath = req.body['relativePath'] || path.sep;
|
454 |
-
|
455 |
-
logger.log.log('verbose', `Got a [${restUtls.STORAGE.URLS.LOAD_FILE_FROM_STORAGE}] request from the [${username}] user for [relativePath=${relativePath}]`);
|
456 |
-
|
457 |
-
if (!security.hasReadPermission(username)) {
|
458 |
-
logger.log.error('The [%s] user doesn\'t have read permissions to load JavaScript files', username);
|
459 |
-
security.sendError(res, 'No read permissions');
|
460 |
-
return;
|
461 |
-
}
|
462 |
-
|
463 |
-
const currentTime = new Date().getTime();
|
464 |
-
|
465 |
-
return storageUtils.loadFileFromStorage(relativePath)
|
466 |
-
.then(data => {
|
467 |
-
const body = {};
|
468 |
-
body[di.FILE_BODY] = data;
|
469 |
-
body[di.FILE_LOAD_TIME] = currentTime;
|
470 |
-
res.send(body);
|
471 |
-
logger.log.debug(`Loaded content of [${relativePath}] JavaScript file by [${username}] user`);
|
472 |
-
})
|
473 |
-
.catch(
|
474 |
-
(err) => {
|
475 |
-
logger.log.error('Failed to load a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
476 |
-
security.sendError(res, 'Failed to load file');
|
477 |
-
});
|
478 |
-
});
|
479 |
-
|
480 |
-
//////////////////////////////////////////////////////////////////////////////
|
481 |
-
// save file to storage
|
482 |
-
//////////////////////////////////////////////////////////////////////////////
|
483 |
-
router.post(restUtls.STORAGE.URLS.SAVE_FILE_TO_STORAGE, function (req, res, next) {
|
484 |
-
const username = security.getLoggedInUsername(req);
|
485 |
-
const relativePath = req.body['relativePath'];
|
486 |
-
const content = req.body['content'];
|
487 |
-
const fileLoadTime = req.body[di.FILE_LOAD_TIME];
|
488 |
-
|
489 |
-
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}]`);
|
490 |
-
|
491 |
-
// validating ( must not empty string )
|
492 |
-
if (!j79.isString(relativePath) || relativePath.length < 1) {
|
493 |
-
logger.log.error('Invalid relativePath');
|
494 |
-
security.sendError(res, 'Invalid relativePath');
|
495 |
-
return;
|
496 |
-
}
|
497 |
-
|
498 |
-
if (!security.hasWritePermission(username)) {
|
499 |
-
logger.log.error('The [%s] user doesn\'t have write permissions to save nexl JavaScript file', username);
|
500 |
-
security.sendError(res, 'No write permissions');
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
|
504 |
-
return storageUtils.saveFileToStorage(relativePath, content, fileLoadTime)
|
505 |
-
.then(result => {
|
506 |
-
res.send(result);
|
507 |
-
logger.log.log('verbose', `The [${relativePath}] file is saved by [${username}] user`);
|
508 |
-
})
|
509 |
-
.catch(
|
510 |
-
(err) => {
|
511 |
-
logger.log.error('Failed to save a [%s] nexl JavaScript file for [%s] user. Reason : [%s]', relativePath, username, utils.formatErr(err));
|
512 |
-
security.sendError(res, 'Failed to save file');
|
513 |
-
});
|
514 |
-
});
|
515 |
-
|
516 |
-
//////////////////////////////////////////////////////////////////////////////
|
517 |
-
// undeclared routes
|
518 |
-
//////////////////////////////////////////////////////////////////////////////
|
519 |
-
router.post('/*', function (req, res) {
|
520 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
521 |
-
security.sendError(res, `Unknown route`, 404);
|
522 |
-
});
|
523 |
-
|
524 |
-
router.get('/*', function (req, res) {
|
525 |
-
logger.log.error(`Unknown route [${req.baseUrl}]`);
|
526 |
-
security.sendError(res, `Unknown route`, 404);
|
527 |
-
});
|
528 |
-
|
529 |
-
// --------------------------------------------------------------------------------
|
530 |
-
module.exports = router;
|
531 |
-
// --------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|