language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Vault{
constructor(){
WildEmitter.mixin(this);
this.id = null;
this.pkfp;
this.initialized = false;
this.admin = null;
this.adminKey = null;
this.topics = {};
this.password = null;
this.publicKey = null;
this.privateKey = null;
this.handlers;
this.messageQueue;
this.version;
this.pendingInvites = {}
this.initHandlers();
}
static registerVault(password, confirm, version){
return new Promise((resolve, reject) => {
setTimeout(()=>{
try{
let result = verifyPassword(password.value.trim(), confirm.value.trim());
if(result !== undefined ){
reject(new Error(result));
}
let vault = new Vault();
vault.init(password.value.trim(), version);
let vaultEncData = vault.pack();
let vaultPublicKey = vault.publicKey;
let ic = new iCrypto();
ic.generateRSAKeyPair("adminkp")
.createNonce("n")
.privateKeySign("n", "adminkp", "sign")
.bytesToHex("n", "nhex");
console.log(`Hash: ${vaultEncData.hash}`)
if(!vaultEncData.hash){
throw new Error("NO HASH!")
}
XHR({
type: "POST",
url: "/register",
dataType: "json",
data: {
nonce: ic.get('nhex'),
sign: ic.get("sign"),
vault: vaultEncData.vault,
vaultHash: vaultEncData.hash,
vaultSign: vaultEncData.sign,
vaultPublicKey: vaultPublicKey,
},
success: (data, statusText, res) => {
if(res.status >= 400){
reject(new Error(`Vault registration error: ${res.statusText} Response code ${res.status}, `))
return;
} else {
console.log("VAULT REGISTER SUCCESS");
resolve();
}
},
error: err => {
console.log(`VAULT REGISTER ERROR: ${err}`);
reject(err);
}
});
}catch (err){
reject(err)
}
}, 50)
})
}
static registerAdminVault(passwdEl, confirmEl, version){
return new Promise((resolve, reject)=>{
let password = passwdEl.value.trim()
let result = verifyPassword(password, confirmEl.value.trim());
if(result !== undefined ){
throw new Error(result);
}
let ic = new iCrypto();
ic.generateRSAKeyPair("adminkp")
.createNonce("n")
.privateKeySign("n", "adminkp", "sign")
.bytesToHex("n", "nhex");
let vault = new Vault();
vault.initAdmin(password, ic.get("adminkp").privateKey, version);
let vaultEncData = vault.pack();
let vaultPublicKey = vault.publicKey;
let adminPublicKey = ic.get("adminkp").publicKey;
console.log(`sending register request. Hash: ${vaultEncData.hash}`);
XHR({
type: "POST",
url: "/admin",
dataType: "json",
data: {
action: "admin_setup",
adminPublickKey: adminPublicKey,
hash: vaultEncData.hash,
nonce: ic.get('nhex'),
sign: ic.get("sign"),
vault: vaultEncData.vault,
vaultPublicKey: vaultPublicKey,
vaultSign: vaultEncData.sign
},
success: () => {
console.log("Success admin register");
resolve();
},
error: err => {
console.log(err.message);
reject("Fail!" + err);
}
});
})
}
// Given raw topic data as arguments encrytps with password and returns cipher
prepareVaultTopicRecord(version = Err.required("Version"),
pkfp = Err.required("pkfp"),
privateKey = Err.required("Private key"),
name = Err.required("Name"),
settings,
comment){
let topicBlob = JSON.stringify({
version: version,
name: name,
key: privateKey,
settings: settings,
comment: comment,
pkfp: pkfp
})
let ic = new iCrypto()
ic.createNonce("salt", 128)
.encode("salt", "hex", "salt-hex")
.createPasswordBasedSymKey("key", this.password, "salt-hex")
.addBlob("topic", topicBlob)
.AESEncrypt("topic", "key", "cipher", true, "CBC", "utf8")
.merge(["salt-hex", "cipher"], "blob")
.setRSAKey("priv", this.privateKey, "private")
.privateKeySign("cipher", "priv", "sign")
.encodeBlobLength("sign", 3, "0", "sign-length")
.merge(["blob", "sign", "sign-length"], "res")
return ic.get("res")
}
initHandlers(){
let self = this;
this.handlers = {};
this.handlers[Internal.POST_LOGIN_DECRYPT] = (msg)=>{ self.emit(Internal.POST_LOGIN_DECRYPT, msg) }
this.handlers[Events.POST_LOGIN_SUCCESS] = ()=>{ self.emit(Events.POST_LOGIN_SUCCESS); }
this.handlers[Internal.TOPIC_CREATED] = (msg)=>{
self.addNewTopic(self, msg)
self.emit(Internal.TOPIC_CREATED, msg.body.topicPkfp)
}
this.handlers[Internal.TOPIC_DELETED] = (msg) =>{
console.log(`TOPIC DELETED: ${msg.body.topicPkfp}`)
delete self.topics[msg.body.topicPkfp];
self.emit(Internal.TOPIC_DELETED, msg.body.topicPkfp);
}
this.handlers[Events.VAULT_UPDATED] = () =>{
console.log("Vault updated in vault");
self.emit(Events.VAULT_UPDATED);
}
this.handlers[Internal.SESSION_KEY] = (msg)=>{
if(!Message.verifyMessage(msg.body.sessionKey, msg)){
throw new Error("Session key signature is invalid!")
}
self.sessionKey = msg.body.sessionKey;
self.emit(Internal.SESSION_KEY, msg)
}
}
/**
* Given a password creates an empty vault
* with generated update private key inside
* @param password
* @returns {Vault}
*/
init(password = Err.required(),
version = Err.required("Version required")){
if(!password || password.trim === ""){
throw new Error("Password required");
}
//CHECK password strength and reject if not strong enough
let ic = new iCrypto();
ic.generateRSAKeyPair("kp")
.getPublicKeyFingerprint("kp", "pkfp")
//Create new Vault object
this.password = password;
this.topics = {};
this.privateKey = ic.get("kp").privateKey;
this.publicKey = ic.get("kp").publicKey;
this.pkfp = ic.get("pkfp");
this.version = version;
this.initialized = true;
this.getPrivateKey = ()=>{ return ic.get("kp").privateKey }
}
/**
* Given a password and a key
* initializes a vault, creates update key
* sets it to admin vault and sets admin private key
*
* @param password
* @param adminKey
* @returns {Vault}
*/
initAdmin(password, adminKey, version = Err.required("Version required!")){
this.init(password, version);
this.admin = true;
this.adminKey = adminKey;
}
async initSaved(version = Err.required("Current chat version"),
vault_encrypted = Err.required("Vault parse: data parameter missing"),
password = Err.required("Vault parse: password parameter missing"),
topics={}){
let ic = new iCrypto();
//console.log(`Salt: ${vault_encrypted.substring(0, 256)}`)
//console.log(`Vault: ${vault_encrypted.substr(256)}`)
ic.addBlob("s16", vault_encrypted.substring(0, 256))
.addBlob("v_cip", vault_encrypted.substr(256))
.hexToBytes("s16", "salt")
.createPasswordBasedSymKey("sym", password, "s16")
.AESDecrypt("v_cip", "sym", "vault_raw", true);
//Populating new object
let data = JSON.parse(ic.get("vault_raw"));
this.adminKey = data.adminKey;
this.admin = data.admin;
this.publicKey = data.publicKey;
this.privateKey = data.privateKey;
this.password = password;
if(!data.pkfp){
ic.setRSAKey("pub", data.publicKey, "public")
.getPublicKeyFingerprint("pub", "pkfp");
this.pkfp = ic.get("pkfp");
} else {
this.pkfp = data.pkfp;
}
let unpackedTopics = this.unpackTopics(topics, password)
if (unpackedTopics){
for(let pkfp of Object.keys(unpackedTopics)){
console.log(`INITIALIZING TOPIC ${pkfp}`);
this.topics[pkfp] = new Topic(
this.version,
pkfp,
unpackedTopics[pkfp].name,
unpackedTopics[pkfp].key,
unpackedTopics[pkfp].comment
)
}
}
if (!data.version || semver.lt(data.version, "2.0.0")){
// TODO format update required!
console.log(`vault format update required to version ${version}`)
let self = this;
this.version = version;
this.versionUpdate = async ()=>{
console.log("!!!Version update lambda");
await self.updateVaultFormat(data)
};
}
this.initialized = true;
}
async updateVaultFormat(data){
if (typeof data.topics === "object"){
Object.keys(data.topics).forEach((pkfp)=>{
this.topics[pkfp] = new Topic(
this.version,
pkfp,
data.topics[pkfp].name,
data.topics[pkfp].key,
data.topics[pkfp].comment);
});
}
this.save("update_format")
}
setId(id = Err.required("ID is required")){
this.id = id;
}
getId(){
return this.id;
}
isAdmin(){
return this.admin;
}
async bootstrap(arrivalHub, messageQueue ,version){
let self = this;
this.version = version;
this.arrivalHub = arrivalHub;
this.messageQueue = messageQueue;
this.arrivalHub.on(this.id, (msg)=>{
self.processIncomingMessage(msg, self);
})
if(this.versionUpdate){
console.log("Updating vault to new format..");
await this.versionUpdate();
}
}
renameTopic(pkfp, name){
assert(this.topics[pkfp], `Topic ${pkfp} does not exist`)
let topic = this.topics[pkfp]
topic.setTopicName(name);
this.save(Internal.TOPIC_UPDATED);
}
processIncomingMessage(msg, self){
console.log("Processing vault incoming message");
if (msg.headers.error){
throw new Error(`Error received: ${msg.headers.error}. WARNING ERROR HADLING NOT IMPLEMENTED!!!`)
}
if (!self.handlers.hasOwnProperty(msg.headers.command)){
console.error(`Invalid vault command received: ${msg.headers.command}`)
return
}
self.handlers[msg.headers.command](msg);
}
// Saves current sate of the vault on the island
// cause - cause for vault update
save(cause){
if (!this.password || !this.privateKey || !this.topics){
throw new Error("Vault object structure is not valid");
}
let { vault, topics, hash, sign } = this.pack();
let message = new Message(this.version);
message.setSource(this.id);
message.setCommand(Internal.SAVE_VAULT);
message.addNonce();
message.body.vault = vault;
message.body.sign = sign;
message.body.hash = hash;
message.body.topics = topics;
message.body.cause = cause;
message.signMessage(this.privateKey);
console.log("SAVING VAULT");
this.messageQueue.enqueue(message)
}
changePassword(newPassword){
if(!this.initialized){
throw new Error("The vault hasn't been initialized");
}
if(!newPassword || newPassword.trim === ""){
throw new Error("Password required");
}
this.password = newPassword;
}
// Encrypts all topics and returns an object of
// pkfp: cipher encrypted topics
packTopics(){
let res = {}
for(let pkfp of Object.keys(this.topics)){
let topic = this.topics[pkfp]
res[pkfp] = this.prepareVaultTopicRecord(
this.version,
topic.pkfp,
topic.privateKey,
topic.name,
topic.settings,
topic.comment
);
}
return res;
}
// Given topics object of pkfp: cipher
// decrypts each cipher and JSON parses with password
// returns object of pkfp: { topic raw data }
unpackTopics(topics){
let res = {};
for(let pkfp of Object.keys(topics)){
res[pkfp] = this.decryptTopic(topics[pkfp], this.password);
}
return res;
}
// Decrypts topic blob with password
decryptTopic(topicBlob, password){
let signLength = parseInt(topicBlob.substr(topicBlob.length - 3))
let signature = topicBlob.substring(topicBlob.length - signLength - 3, topicBlob.length - 3);
let salt = topicBlob.substring(0, 256);
let topicCipher = topicBlob.substring(256, topicBlob.length - signLength - 3);
let ic = new iCrypto();
ic.setRSAKey("pub", this.publicKey, "public")
.addBlob("cipher", topicCipher)
.addBlob("sign", signature)
.publicKeyVerify("cipher", "sign", "pub", "verified")
if(!ic.get("verified")) throw new Error("Topic signature is invalid!")
ic.addBlob("salt-hex", salt)
.createPasswordBasedSymKey("sym", password, "salt-hex")
.AESDecrypt("cipher", "sym", "topic-plain", true)
return JSON.parse(ic.get("topic-plain"));
}
addNewTopic(self, data){
//if(!Message.verifyMessage(self.sessionKey, data)){
// throw new Error("Session key signature is invalid!")
//}
console.log(`Adding new topic to vault`)
let vaultRecord = data.body.vaultRecord;
let metadata = data.body.metadata;
let topicData = self.decryptTopic(vaultRecord, self.password);
let pkfp = topicData.pkfp;
let newTopic = new Topic(
this.version,
pkfp,
topicData.name,
topicData.key,
topicData.comment
)
console.log(`New topic initialized: ${pkfp}, ${topicData.name} `)
newTopic.loadMetadata(metadata);
newTopic.bootstrap(self.messageQueue, self.arrivalHub, self.version);
self.topics[pkfp] = newTopic;
if (self.pendingInvites.hasOwnProperty(data.body.inviteCode)){
let inviteeNickname = self.pendingInvites[data.body.inviteCode].nickname
console.log(`Initialize settings on topic join. Invitee ${inviteeNickname}`);
self.initSettingsOnTopicJoin(self, pkfp, inviteeNickname, data)
}
self.emit(Events.TOPIC_CREATED, pkfp);
return pkfp
}
pack(){
let vaultBlob = JSON.stringify({
version: this.version,
publicKey: this.publicKey,
privateKey: this.privateKey,
admin: this.admin,
adminKey: this.adminKey,
settings: this.settings
});
let ic = new iCrypto();
ic.createNonce("salt", 128)
.encode("salt","hex", "salt-hex")
.createPasswordBasedSymKey("key", this.password, "salt-hex")
.addBlob("vault", vaultBlob)
.AESEncrypt("vault", "key", "cip-hex", true, "CBC", "utf8")
.merge(["salt-hex", "cip-hex"], "res")
.hash("res", "vault-hash")
.setRSAKey("asymkey", this.privateKey, "private")
.privateKeySign("vault-hash", "asymkey", "sign");
let topics = this.packTopics(this.password)
//console.log(`Salt: ${ic.get("salt-hex")}`)
//console.log(`Vault: ${ic.get("cip-hex")}`)
//Sign encrypted vault with private key
return {
vault: ic.get("res"),
topics: topics,
hash : ic.get("vault-hash"),
sign : ic.get("sign")
}
}
processNewTopicEvent(self, data){
//verify session key
let metadata = data.body.metadata;
}
addTopic(pkfp, name, privateKey, comment){
if (this.topics.hasOwnProperty(pkfp)) throw new Error("Topic with such id already exists");
let newTopic = new Topic(this.version, pkfp, name, privateKey, comment)
this.topics[pkfp] = newTopic;
return newTopic
}
removeTopic(){
}
//Only adds initialized topic to vault topics
registerTopic(topic = Err.required()){
console.log(`Registring topic ${topic.pkfp}`);
this.topics[topic.pkfp] = topic;
}
} |
JavaScript | class Application extends EventEmitter {
/**
* <strong>Note:</strong> The constructor is not accessible from the client
* code. Instances are created using module's
* [createApplication()]{@link module:x2node-ws.createApplication} function.
*
* @protected
* @param {module:x2node-ws~ApplicationOptions} options Application
* configuration options.
*/
constructor(options) {
super();
// save options
this._options = options;
// application API version
if (options.apiVersion === undefined) {
if (process.env.NODE_ENV === 'development') {
this._apiVersion = `dev-${Date.now()}`;
} else {
this._apiVersion =
require.main.require('./package.json').version;
}
} else {
this._apiVersion = String(options.apiVersion);
}
// allowed CORS origins
if (Array.isArray(options.allowedOrigins) &&
(options.allowedOrigins.length > 0))
this._allowedOrigins = new Set(
options.allowedOrigins.map(o => String(o).toLowerCase()));
else if (((typeof options.allowedOrigins) === 'string') &&
(options.allowedOrigins.trim().length > 0))
this._allowedOrigins = new Set(
options.allowedOrigins.toLowerCase().trim().split(/\s*,\s*/));
// the debug log
this._log = common.getDebugLogger('X2_APP');
// marshallers, authenticators, authorizers and endpoints (later maps)
this._marshallers = new Array();
this._authenticators = new Array();
this._authorizers = new Array();
this._endpoints = new Array();
// current URIs prefix
this._prefix = '';
// application running state
this._connections = new Map();
this._nextConnectionId = 1;
this._running = false;
this._shuttingDown = false;
}
/**
* Set URI prefix for the subsequent <code>addAuthenticator()</code>,
* <code>addAuthorizer()</code> and <code>addEndpoint()</code> calls.
*
* @param {string} prefix Prefix to add to the URI patterns.
* @returns {module:x2node-ws~Application} This application.
*/
setPrefix(prefix) {
this._prefix = (prefix || '');
return this;
}
/**
* Add marshaller for the content type. When looking up marshaller for a
* content type, the content type patterns are matched in the order the
* marshallers were added to the application. After all custom marshallers
* are added, the application automatically adds default JSON marshaller
* implementation for patterns "application/json" and ".+\+json".
*
* @param {string} contentTypePattern Content type regular expression
* pattern. The content type is matched against the pattern as a whole, so no
* starting <code>^</code> and ending <code>$</code> are necessary. It is
* matched without any parameters (such as charset, etc.). Also, the match is
* case-insensitive.
* @param {module:x2node-ws.Marshaller} marshaller The marshaller
* implementation.
* @returns {module:x2node-ws~Application} This application.
*/
addMarshaller(contentTypePattern, marshaller) {
if (this._running)
throw new common.X2UsageError('Application is already running.');
this._marshallers.push({
pattern: contentTypePattern,
value: marshaller
});
return this;
}
/**
* Associate an authenticator with the specified URI pattern. When looking up
* authenticator for a URI, the URI patterns are matched in the order the
* authenticators were added to the application.
*
* @param {string} uriPattern URI regular expression pattern. The URI is
* matched against the pattern as a whole, so no starting <code>^</code> and
* ending <code>$</code> are necessary. The match is case-sensitive.
* @param {module:x2node-ws.Authenticator} authenticator The authenticator.
* @returns {module:x2node-ws~Application} This application.
*/
addAuthenticator(uriPattern, authenticator) {
if (this._running)
throw new common.X2UsageError('Application is already running.');
this._authenticators.push(
this._toMappingDesc(uriPattern, authenticator));
return this;
}
/**
* Associate an authorizer with the specified URI pattern. When looking up
* authorizer for a URI, the URI patterns are matched in the order the
* authorizers were added to the application.
*
* @param {string} uriPattern URI regular expression pattern. The URI is
* matched against the pattern as a whole, so no starting <code>^</code> and
* ending <code>$</code> are necessary. The match is case-sensitive.
* @param {(module:x2node-ws.Authorizer|function)} authorizer The authorizer.
* If function, the function is used as the authorizer's
* <code>isAllowed()</code> method.
* @returns {module:x2node-ws~Application} This application.
*/
addAuthorizer(uriPattern, authorizer) {
if (this._running)
throw new common.X2UsageError('Application is already running.');
this._authorizers.push(
this._toMappingDesc(uriPattern, (
(typeof authorizer) === 'function' ?
{ isAllowed: authorizer } : authorizer
)));
return this;
}
/**
* Add web service endpoint. When looking up endpoint handler for a URI, the
* URI patterns are matched in the order the handlers were added to the
* application.
*
* @param {(string|Array.<string>)} uriPattern Endpoint URI regular
* expression pattern. URI parameters are groups in the pattern. The URI is
* matched against the pattern as a whole, so no starting <code>^</code> and
* ending <code>$</code> are necessary. The match is case-sensitive. If
* array, the first array element is the pattern and the rest are names for
* the positional URI parameters.
* @param {module:x2node-ws.Handler} handler The handler for the endpoint.
* @returns {module:x2node-ws~Application} This application.
*/
addEndpoint(uriPattern, handler) {
if (this._running)
throw new common.X2UsageError('Application is already running.');
this._endpoints.push(
this._toMappingDesc(uriPattern, handler));
return this;
}
/**
* Create mapping descriptor.
*
* @private
* @param {(string|Array.<string>)} uriPattern URI pattern.
* @param {*} value The mapping value.
* @returns {module:x2node-ws~PatternMap~MappingDesc} Mapping descriptor.
*/
_toMappingDesc(uriPattern, value) {
return {
pattern: (
this._prefix.length > 0 ? (
Array.isArray(uriPattern) ?
[ this._prefix + uriPattern[0] ].concat(
uriPattern.slice(1))
: this._prefix + uriPattern
) : uriPattern
),
value: value
};
}
/**
* Create HTTP server and run the application on it.
*
* @param {number} port Port, on which to listen for incoming HTTP requests.
* @returns {http.external:Server} The HTTP server.
*/
run(port) {
// check if already running
if (this._running)
throw new common.X2UsageError('Application is already running.');
this._running = true;
// the debug log
const log = this._log;
log('starting up');
// add default marshallers
this._marshallers.push({
pattern: 'application/json',
value: JSON_MARSHALLER
});
this._marshallers.push({
pattern: '.+\\+json',
value: JSON_MARSHALLER
});
// compile pattern maps
this._marshallers = new PatternMap(this._marshallers);
this._authenticators = new PatternMap(this._authenticators);
this._authorizers = new PatternMap(this._authorizers);
this._endpoints = new PatternMap(this._endpoints);
// create HTTP server
const server = http.createServer();
// set initial connection idle timeout
server.setTimeout(
this._options.connectionIdleTimeout || DEFAULT_CONN_IDLE_TIMEOUT,
onBeforeResponseTimeout
);
// set maximum allowed number of HTTP request headers
server.maxHeadersCount = (this._options.maxRequestHeadersCount || 50);
// set open connections registry maintenance handlers
server.on('connection', socket => {
const connectionId = `#${this._nextConnectionId++}`;
this._log(`connection ${connectionId}: opened`);
socket[CONNECTION_ID] = connectionId;
socket[NEXT_CALL_ID] = 1;
socket.x2NextCallId = nextCallId.bind(socket);
socket[IDLE] = true;
socket[CALLS] = [];
this._connections.set(CONNECTION_ID, socket);
socket.on('close', () => {
this._log(`connection ${connectionId}: closed`);
this._connections.delete(CONNECTION_ID);
for (let call of socket[CALLS])
call.connectionClosed = true;
delete socket[CALLS];
});
});
// set shutdown handler
server.on('close', () => {
log('all connections closed, firing shutdown event');
this.emit('shutdown');
});
// set request processing handlers
server.on('checkContinue', this._respond.bind(this));
server.on('request', this._respond.bind(this));
// setup signals
const terminate = (singalNum) => {
if (this._shuttingDown) {
log('already shutting down');
} else {
log('shutting down');
// mark application as shutting down
this._shuttingDown = true;
// stop accepting new connections
server.close(() => {
process.exit(128 + singalNum);
});
// severe idle keep-alive connections
for (let connection of this._connections.values())
if (connection[IDLE])
this._destroyConnection(connection);
// fire shutting down event
this.emit('shuttingdown');
}
};
process.on('SIGHUP', () => { terminate(1); });
process.on('SIGINT', () => { terminate(2); });
process.on('SIGTERM', () => { terminate(15); });
process.on('SIGBREAK', () => { terminate(21); });
// terminate on server error
server.on('error', err => {
common.error('could not start the application', err);
terminate(-127);
});
// start listening for incoming requests
server.listen(port, () => {
log(
`ready for requests on ${port}, ` +
`API version ${this._apiVersion}`);
});
// return the HTTP server
return server;
}
/**
* Respond to an HTTP request.
*
* @private
* @param {http.external:IncomingMessage} httpRequest HTTP request.
* @param {http.external:ServerResponse} httpResponse HTTP response.
*/
_respond(httpRequest, httpResponse) {
// mark connection as active
httpRequest.socket[IDLE] = false;
// create the service call object
const call = new ServiceCall(
this._apiVersion, httpRequest, this._options);
// add call to the calls associated with the connection
httpRequest.socket[CALLS].push(call);
// process the call
try {
// log the call
this._log(
`call ${call.id}: received ${httpRequest.method}` +
` ${call.requestUrl.pathname}`);
// remove the initial connection idle timeout
httpRequest.socket.setTimeout(0, onBeforeResponseTimeout);
// lookup the handler
const hasHandler = this._endpoints.lookup(
call.requestUrl.pathname,
(handler, uriParams) => { call.setHandler(handler, uriParams); }
);
if (!hasHandler)
return this._sendResponse(
httpResponse, call, (new ServiceResponse(404).setEntity({
errorCode: 'X2-404-1',
errorMessage: 'No service endpoint at this URI.'
})));
// lookup the authenticator (OPTIONS responder needs it)
this._authenticators.lookup(
call.requestUrl.pathname,
authenticator => { call.setAuthenticator(authenticator); }
);
// get handler methods
const handlerMethods = this._getHandlerMethods(call.handler);
// get requested method
const method = (
httpRequest.method === 'HEAD' ? 'GET' : httpRequest.method);
// respond to an OPTIONS request
if (method === 'OPTIONS')
return this._sendOptionsResponse(
httpResponse, call, handlerMethods);
// check if the method is supported by the handler
if (!handlerMethods.has(method)) {
const response = new ServiceResponse(405);
this._setAllowedMethods(response, handlerMethods);
response.setEntity({
errorCode: 'X2-405-1',
errorMessage: 'Method not supported by the service endpoint.'
});
return this._sendResponse(httpResponse, call, response);
}
// lookup the authorizer
this._authorizers.lookupMultiReverse(
call.requestUrl.pathname,
authorizer => { call.addAuthorizer(authorizer); }
);
// build the processing chain
this._authenticateCall(
call
).then(
call => (
this._log(
`call ${call.id}: authed actor` +
` ${call.actor && call.actor.stamp}`),
this._authorizeCall(call)
)
).then(
call => this._chooseRepresentation(call)
).then(
call => this._readRequestPayload(call, httpResponse)
).then(
call => Promise.resolve(call.handler[method](call))
).then(
result => {
let response;
if ((result === null) || (result === undefined)) {
response = new ServiceResponse(204);
} else if (result instanceof ServiceResponse) {
response = result;
} else if ((typeof result) === 'object') {
response = new ServiceResponse(200);
response.setEntity(result);
} else {
response = new ServiceResponse(200);
response.setEntity(
Buffer.from(String(result), 'utf8'),
'text/plain; charset=UTF-8'
);
}
this._sendResponse(httpResponse, call, response);
}
).catch(
err => {
if (err instanceof ServiceResponse)
this._sendResponse(httpResponse, call, err);
else if (err)
this._sendInternalServerErrorResponse(
httpResponse, call, err);
}
);
} catch (err) {
this._sendInternalServerErrorResponse(httpResponse, call, err);
}
}
/**
* Perform service call authentication, set the actor on the call and check
* if allowed to proceed.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @returns {Promise.<module:x2node-ws~ServiceCall>} Promise of the
* authenticated call.
*/
_authenticateCall(call) {
// check if no authenticator
if (!call.authenticator)
return Promise.resolve(call);
// call the authenticator
return Promise.resolve(call.authenticator.authenticate(call)).then(
actor => {
// check if connection closed while authenticating
if (call.connectionClosed)
return Promise.reject(null);
// set actor on the call
if (actor)
call.actor = actor;
// proceed with the call
return call;
}
);
}
/**
* Perform service call authorization.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @returns {Promise.<module:x2node-ws~ServiceCall>} Promise of the
* authorized call.
*/
_authorizeCall(call) {
// pre-authorize the call
call.authorized = true;
// check if no authorizers
const authorizers = call.authorizers;
if (!authorizers || (authorizers.length === 0))
return call;
// queue up the authorizers
let promiseChain = Promise.resolve(call);
for (let authorizer of authorizers) {
promiseChain = promiseChain.then(
call => {
// check if connection closed while authorizing
if (call.connectionClosed)
return Promise.reject(null);
// check if unauthorized by previous authorizer
if (!call.authorized)
return call;
// call the authorizer
return Promise.resolve(authorizer.isAllowed(call)).then(
authorized => {
// check if connection closed while authorizing
if (call.connectionClosed)
return Promise.reject(null);
// check if unauthorized
if (!authorized)
call.authorized = false;
// proceed with the call
return call;
}
);
}
);
}
// queue up the authorization check and return the result
return promiseChain.then(
call => {
// check if failed to authorize
if (!call.authorized)
return Promise.reject(
call.actor ?
(new ServiceResponse(403)).setEntity({
errorCode: 'X2-403-1',
errorMessage: 'Insufficient permissions.'
}) :
(new ServiceResponse(401)).setEntity({
errorCode: 'X2-401-1',
errorMessage: 'Authentication required.'
})
);
// authorized, proceed with the call
return call;
}
);
}
/**
* Analyze "Accept" request header, if any, and choose response content type.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @returns {Promise.<module:x2node-ws~ServiceCall>} Promise of the call with
* the requested representation set.
*/
_chooseRepresentation(call) {
// get list of supported representations from the handler
const handler = call.handler;
const representations = (
(typeof handler.getRepresentations) === 'function' ?
handler.getRepresentations(call)
: [ 'application/json' ]
);
// check if has "Accept" header
const acceptHeader = call.httpRequest.headers['accept'];
// set default representation if no "Accept" header
if (!acceptHeader) {
call.requestedRepresentation = representations[0];
return call;
}
// parse "Accept" header
let invalid = false;
const acceptedRepresentations = acceptHeader.trim().toLowerCase().split(
/\s*,\s*/
).map(rangeDef => {
const m = ACCEPT_HEADER_RANGE_PATTERN.exec(rangeDef);
const range = (m && m[1]);
if (!range || /^\*\/[^*]/.test(range)) {
invalid = true;
return {};
}
const precision = (
range === '*/*' ? 2 : (
range.endsWith('/*') ? 1 : 0
)
);
let testFunc;
switch (precision) {
case 0:
testFunc = v => (v === range);
break;
case 1:
testFunc = v => v.startsWith(
range.substring(0, range.length - 1));
break;
case 2:
testFunc = () => true;
}
return {
test: testFunc,
precision: precision,
weight: (m[2] !== undefined ? Number(m[2]) : 1)
};
}).sort((a, b) => (
a.precision > b.precision ? -1 : (
a.precision < b.precision ? 1 : (
a.weight > b.weight ? -1 : (
a.weight < b.weight ? 1 : 0
)
)
)
));
if (invalid)
return Promise.reject((new ServiceResponse(400)).setEntity({
errorCode: 'X2-400-2',
errorMessage: 'Malformed Accept request header.'
}));
// select representation
const numAcceptedReps = acceptedRepresentations.length;
let selectedRepresentation, selectedWeight = numAcceptedReps;
for (let representation of representations) {
for (let weight = 0; weight < numAcceptedReps; weight++) {
const range = acceptedRepresentations[weight];
if (range.test(representation) && (weight < selectedWeight)) {
selectedRepresentation = representation;
selectedWeight = weight;
}
}
}
// got matching representation?
if (!selectedRepresentation)
return Promise.reject((new ServiceResponse(406)).setEntity({
errorCode: 'X2-406',
errorMessage: 'Unable to provide acceptable representation.'
}));
// set it in the call
call.requestedRepresentation = selectedRepresentation;
// continue call processing
return call;
}
/**
* Load request payload, if any, and add it to the service call.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {http.external:ServerResponse} httpResponse The HTTP response.
* @returns {Promise.<module:x2node-ws~ServiceCall>} Promise of the call with
* payload added to it.
*/
_readRequestPayload(call, httpResponse) {
// get request headers
const requestHeaders = call.httpRequest.headers;
// check if there is payload
const contentLength = Number(requestHeaders['content-length']);
if (!(contentLength > 0))
return call;
// check if not too large
const maxRequestSize = (
this._options.maxRequestSize || DEFAULT_MAX_REQUEST_SIZE);
if (contentLength > maxRequestSize)
return Promise.reject(
(new ServiceResponse(413))
.setHeader('Connection', 'close')
.setEntity({
errorCode: 'X2-413',
errorMessage: 'The request entity is too large.'
})
);
// get content type
const contentType = (
requestHeaders['content-type'] || 'application/octet-stream');
// restore connection idle timeout
const connection = call.httpRequest.socket;
connection.setTimeout(
this._options.connectionIdleTimeout || DEFAULT_CONN_IDLE_TIMEOUT,
onBeforeResponseTimeout
);
// check if multipart
if (/^multipart\//i.test(contentType)) {
// TODO: implement
return Promise.reject((new ServiceResponse(415)).setEntity({
errorCode: 'X2-415',
errorMessage: 'Multipart requests are not supported yet.'
}));
} else { // not multipart
// find marshaller
const entityContentType = contentType.split(';')[0].toLowerCase();
let marshaller;
if (call.handler.requestEntityParsers) {
const deserializer = call.handler.requestEntityParsers[
entityContentType];
if ((typeof deserializer) === 'function')
marshaller = { deserialize: deserializer };
}
if (!marshaller)
marshaller = this._marshallers.lookup(entityContentType);
if (!marshaller)
return Promise.reject(
(new ServiceResponse(415)).setEntity({
errorCode: 'X2-415',
errorMessage: 'Unsupported request entity content type.'
})
);
// respond with 100 if expecting continue
this._sendContinue(httpResponse);
// read the data
return this._readEntity(
call, call.httpRequest, marshaller, contentType).then(
entity => {
// remove connection idle timeout
connection.setTimeout(0, onBeforeResponseTimeout);
// set entity on the call
call.entity = entity;
call.entityContentType = entityContentType;
// proceed with the call
return call;
},
err => {
// remove connection idle timeout
connection.setTimeout(0, onBeforeResponseTimeout);
// abort the call
return Promise.reject(err);
}
);
}
}
/**
* Read and parse entity from input stream.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {stream.external:Readable} input Input stream.
* @param {module:x2node-ws.Marshaller} marshaller Marshaller to use to parse
* the entity.
* @param {string} contentType Content type request header value.
* @returns {Promise.<Object>} Promise of the parsed entity object.
*/
_readEntity(call, input, marshaller, contentType) {
return (new Promise((resolve, reject) => {
const dataBufs = new Array();
let done = false;
input
.on('data', chunk => {
// check if response resolved in another event handler
if (done)
return;
// check if connection closed
if (call.connectionClosed) {
done = true;
return Promise.reject(null);
}
// add data chunk to the read data buffer
dataBufs.push(chunk);
})
.on('error', err => {
// check if response resolved in another event handler
if (done)
return;
// mark as done
done = true;
// reject with the error
reject(err);
})
.on('end', () => {
// check if response resolved in another event handler
if (done)
return;
// mark as done
done = true;
// check if connection closed
if (call.connectionClosed)
return Promise.reject(null);
// parse the request entity
try {
resolve(marshaller.deserialize((
dataBufs.length === 1 ?
dataBufs[0] : Buffer.concat(dataBufs)
), contentType));
} catch (err) {
this._log(
`call ${call.id}: error parsing request entity:` +
` ${err.message}`);
if (err instanceof common.X2DataError) {
reject(
(new ServiceResponse(400)).setEntity({
errorCode: 'X2-400-1',
errorMessage:
'Could not parse request entity.'
})
);
} else {
reject(err);
}
}
});
})).then( // let all I/O events play out
entity => new Promise(resolve => {
setTimeout(() => { resolve(entity); }, 1);
}),
err => new Promise((_, reject) => {
setTimeout(() => { reject(err); }, 1);
})
);
}
/**
* Send 100 (Continue) HTTP response, if needs to.
*
* @private
* @param {http.external:ServerResponse} httpResponse The HTTP response.
*/
_sendContinue(httpResponse) {
// KLUDGE: response properties used below are undocumented
if (httpResponse._expect_continue && !httpResponse._sent100)
httpResponse.writeContinue();
/*if (httpRequest.headers['expect'] === '100-continue')
httpResponse.writeContinue();*/
}
/**
* Send response to an OPTIONS request.
*
* @private
* @param {http.external:ServerResponse} httpResponse HTTP response.
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {Set.<string>} allowedMethods Allowed HTTP methods.
*/
_sendOptionsResponse(httpResponse, call, allowedMethods) {
// create the response object
const response = new ServiceResponse(200);
// add allowed methods
this._setAllowedMethods(response, allowedMethods);
// add zero content length header
response.setHeader('Content-Length', 0);
// response always varies depending on the "Origin" header
response.setHeader('Vary', 'Origin');
// process CORS preflight request
const requestHeaders = call.httpRequest.headers;
const requestedMethod = requestHeaders['access-control-request-method'];
if (requestedMethod && this._addCORS(call, response)) {
// preflight response caching
response.setHeader(
'Access-Control-Max-Age', (
this._options.corsPreflightMaxAge ||
DEFAULT_CORS_PREFLIGHT_MAX_AGE));
// allowed methods
response.setHeader(
'Access-Control-Allow-Methods', response.headers['allow']);
// allowed request headers
const requestedHeaders =
requestHeaders['access-control-request-headers'];
if (requestedHeaders)
response.setHeader(
'Access-Control-Allow-Headers', requestedHeaders);
}
// custom handler logic
if ((typeof call.handler.OPTIONS) === 'function')
call.handler.OPTIONS(call, response);
// send the response
this._sendResponse(httpResponse, call, response);
}
/**
* Send HTTP 500 (Internal Server Error) response as a reaction to an
* unexpected error.
*
* @private
* @param {http.external:ServerResponse} httpResponse HTTP response.
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {external:Error} err The error that caused the 500 response.
*/
_sendInternalServerErrorResponse(httpResponse, call, err) {
common.error(`call ${call.id}: internal server error`, err);
this._sendResponse(
httpResponse, call, (new ServiceResponse(500))
.setHeader('Connection', 'close')
.setEntity({
errorCode: 'X2-500-1',
errorMessage: 'Internal server error.'
})
);
}
/**
* Send web-service response.
*
* @private
* @param {http.external:ServerResponse} httpResponse HTTP response.
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {module:x2node-ws~ServiceResponse} response The response.
* @param {boolean} [noDelay] If <code>true</code>, response delay logic is
* disabled.
*/
_sendResponse(httpResponse, call, response, noDelay) {
// check if delayed
if (!noDelay && Number.isInteger(this._options.delay)) {
this._log(
`call ${call.id}: delaying response by` +
` ${this._options.delay}ms`);
return setTimeout(() => {
this._sendResponse(httpResponse, call, response, true);
}, this._options.delay);
}
// remove call from the calls associated with the connection
const connectionCalls = httpResponse.socket[CALLS];
if (connectionCalls)
connectionCalls.splice(connectionCalls.indexOf(call), 1);
// check if connection closed
if (call.connectionClosed) {
this._log(
`call ${call.id}: not sending response because` +
` connection was closed`);
return;
}
try {
// restore idle timeout on the connection
httpResponse.setTimeout(
this._options.connectionIdleTimeout || DEFAULT_CONN_IDLE_TIMEOUT,
socket => {
if (!call.complete)
common.error(
`call ${call.id}: connection timed out before` +
' completing the response');
this._destroyConnection(socket);
}
);
// get the request method for quick access
const method = call.httpRequest.method;
// response always varies depending on the "Origin" header
response.addToHeadersListHeader('Vary', 'Origin');
// let authenticator to add its response headers
if (call.authenticator && call.authenticator.addResponseHeaders)
call.authenticator.addResponseHeaders(call, response);
// default response cache control if none in the service response
if (!response.hasHeader('Cache-Control') && (
(method === 'GET') || (method === 'HEAD') ||
response.hasHeader('Content-Location')) &&
CACHEABLE_STATUS_CODES.has(response.statusCode)) {
response
.setHeader('Cache-Control', 'no-cache')
.setHeader('Expires', '0')
.setHeader('Pragma', 'no-cache');
}
// check if cross-origin request
if (this._addCORS(call, response)) {
// add exposed headers
const exposedHeaders = Object.keys(response.headers).filter(
h => !SIMPLE_RESPONSE_HEADERS.has(h)).join(', ');
if (exposedHeaders.length > 0)
response.setHeader(
'Access-Control-Expose-Headers', exposedHeaders);
}
// don't keep connection alive if shutting down
if (this._shuttingDown)
response.setHeader('Connection', 'close');
// completion handler
httpResponse.on('finish', () => {
call.complete = true;
const connection = call.httpRequest.socket;
connection[IDLE] = true;
if (this._shuttingDown)
process.nextTick(() => {
this._destroyConnection(connection);
});
this._log(
`call ${call.id}: completed in ` +
`${Date.now() - call.timestamp}ms`);
});
// add response entities
const entities = response.entities;
if (entities.length > 0) {
// set up response content type
if (entities.length > 1) {
response.setHeader(
'Content-Type', `multipart/mixed; boundary=${BOUNDARY}`);
} else { // single entity
const entity = entities[0];
for (let h of Object.keys(entity.headers))
response.setHeader(h, entity.headers[h]);
}
// send entities using different methods
if (method === 'HEAD') {
this._completeResponseNoEntities(
httpResponse, call, response);
} else {
this._completeResponseWithEntities(
httpResponse, call, response, entities);
}
} else { // no entities
this._completeResponseNoEntities(httpResponse, call, response);
}
} catch (err) {
if (call.responseHeaderWritten) {
common.error(
`call ${call.id}: internal error after response header has` +
' been written, quitely closing the connection', err);
this._destroyConnection(httpResponse.socket);
} else {
common.error(
`call ${call.id}: internal error preparing response,` +
' sending 500 response', err);
try {
httpResponse.socket.end(
'HTTP/1.1 500 ' + http.STATUS_CODES[500] + '\r\n' +
'Date: ' + (new Date()).toUTCString() + '\r\n' +
'Connection: close\r\n' +
'\r\n');
} catch (errorResponseErr) {
common.error(
`call ${call.id}: internal error sending 500 response,` +
' quitely closing the connection', errorResponseErr);
this._destroyConnection(httpResponse.socket);
}
}
}
}
/**
* Forcibly severe connection.
*
* @private
* @param {net.external:Socket} socket The connection socket.
*/
_destroyConnection(socket) {
if (socket && !socket.destroyed) {
const connectionId = socket[CONNECTION_ID];
this._log(`connection ${connectionId}: severing`);
this._connections.delete(connectionId);
socket.destroy();
}
}
/**
* Check origin of a cross-origin request and if allowed, add CORS response
* headers common for simple and preflight requests.
*
* @private
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {module:x2node-ws~ServiceResponse} response The response.
* @returns {boolean} <code>true</code> if CORS headers were added (allowed
* cross-origin request or not a cross-origin request).
*/
_addCORS(call, response) {
const origin = call.httpRequest.headers['origin'];
if (!origin)
return false;
// check if the service allows only specific origins
let allowed = false;
if (this._allowedOrigins) {
// check if allowed
allowed = this._allowedOrigins.has(origin.toLowerCase());
if (allowed) {
// allow the specific origin
response.setHeader('Access-Control-Allow-Origin', origin);
// check if the endpoint supports credentialed requests
if (call.authenticator)
response.setHeader(
'Access-Control-Allow-Credentials', 'true');
}
} else { // service is open to all origins
// allow it
allowed = true;
// check if the endpoint supports credentialed requests
if (call.authenticator) {
response.setHeader('Access-Control-Allow-Origin', origin);
response.setHeader('Access-Control-Allow-Credentials', 'true');
} else { // public endpoint
response.setHeader('Access-Control-Allow-Origin', '*');
}
}
// if allowed, headers were added
return allowed;
}
/**
* Complete sending response with no entities.
*
* @private
* @param {http.external:ServerResponse} httpResponse HTTP response.
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {module:x2node-ws~ServiceResponse} response The response.
*/
_completeResponseNoEntities(httpResponse, call, response) {
httpResponse.writeHead(
response.statusCode, this._capitalizeHeaders(response.headers));
call.responseHeaderWritten = true;
httpResponse.end();
}
/**
* Complete sending response with entities.
*
* @private
* @param {http.external:ServerResponse} httpResponse HTTP response.
* @param {module:x2node-ws~ServiceCall} call The call.
* @param {module:x2node-ws~ServiceResponse} response The response.
* @param {Array.<module:x2node-ws~ServiceResponse~Entity>} entities Entities
* to send.
*/
_completeResponseWithEntities(httpResponse, call, response, entities) {
// create sequence of buffers and streams to send in the response body
let bufs = new Array(), chunked = false;
if (entities.length === 1) {
const entity = entities[0];
if (entity.data instanceof stream.Readable) {
bufs.push(entity.data);
chunked = true;
} else {
bufs.push(this._getResponseEntityDataBuffer(entity));
}
} else { // multipart
// add payload parts
for (let i = 0, len = entities.length; i < len; i++) {
const entity = entities[i];
// part boundary
bufs.push(BOUNDARY_MID);
// part headers
bufs.push(Buffer.from(
Object.keys(entity.headers).reduce((res, h) => {
return res + this._capitalizeHeaderName(h) + ': ' +
entity.headers[h] + '\r\n';
}, '') + '\r\n', 'ascii'));
// part body
if (entity.data instanceof stream.Readable) {
bufs.push(entity.data);
chunked = true;
} else {
bufs.push(this._getResponseEntityDataBuffer(entity));
}
// part end
bufs.push(CRLF);
}
// end boundary of the multipart payload
bufs.push(BOUNDARY_END);
}
// set response content length
if (!chunked)
response.setHeader(
'Content-Length',
bufs.reduce((tot, buf) => (tot + buf.length), 0)
);
// write response head
httpResponse.writeHead(
response.statusCode, this._capitalizeHeaders(response.headers));
call.responseHeaderWritten = true;
// setup error listener
let error = false;
httpResponse.on('error', err => {
this._log(
`call ${call.id}: error writing the response: ${err.message}`);
error = true;
});
// write response body buffers and streams
const numBufs = bufs.length;
let curBufInd = 0;
function writeHttpResponse() {
// give up if error or connection closed
if (error || call.connectionClosed) {
this._log(`call ${call.id}: aborting sending the response`);
return;
}
// write the buffers to the stream
while (curBufInd < numBufs) {
const data = bufs[curBufInd++];
// buffer or stream?
if (Buffer.isBuffer(data)) {
// write the buffer, wait for "drain" if necessary
if (!httpResponse.write(data)) {
// continue to the next buffer or stream upon "drain"
httpResponse.once('drain', writeHttpResponse);
// exit until "drain" is received
return;
}
} else { // stream
// pipe the stream into the response
data.pipe(httpResponse, { end: false });
// continue to the next buffer or stream upon "end"
data.on('end', writeHttpResponse);
// exit until "end" is received
return;
}
}
// all buffers written, end the response
httpResponse.end();
// remove call from the socket
const socketCalls = httpResponse.socket[CALLS];
const callInd = socketCalls.indexOf(call);
if (callInd >= 0)
socketCalls.splice(callInd, 1);
}
// initiate the write
writeHttpResponse();
}
/**
* Get data buffer for the specified response entity invoking appropriate
* marshaller if necessary.
*
* @private
* @param {module:x2node-ws~ServiceResponse~Entity} entity Response entity.
* @returns {external:Buffer} Buffer with the response entity data.
*/
_getResponseEntityDataBuffer(entity) {
if (Buffer.isBuffer(entity.data))
return entity.data;
const contentType = entity.headers['content-type'];
const marshaller = this._marshallers.lookup(contentType.toLowerCase());
if (!marshaller)
throw new common.X2UsageError(
`No marshaller for content type ${contentType}.`);
return marshaller.serialize(entity.data, contentType);
}
/**
* Capitalize header names.
*
* @private
* @param {Object.<string,string>} headers Headers to capitalize.
* @returns {Object.<string,string>} Capitalized headers.
*/
_capitalizeHeaders(headers) {
return Object.keys(headers).reduce((res, h) => {
res[this._capitalizeHeaderName(h)] = headers[h];
return res;
}, new Object());
}
/**
* Capitalize header name.
*
* @private
* @param {string} headerName Header name to capitalize.
* @returns {string} Capitalized header name.
*/
_capitalizeHeaderName(headerName) {
const headerNameLC = headerName.toLowerCase();
const normalizedHeaderName = NORMAL_HEADER_NAMES[headerNameLC];
if (normalizedHeaderName)
return normalizedHeaderName;
return headerNameLC.replace(/\b[a-z]/g, m => m.toUpperCase());
}
/**
* Get HTTP methods supported by the handler.
*
* @private
* @param {module:x2node-ws.Handler} handler The handler.
* @returns {Set.<string>} The supported methods.
*/
_getHandlerMethods(handler) {
let methods = handler[METHODS];
if (!methods) {
handler[METHODS] = methods = new Set();
for (let o = handler; o; o = Object.getPrototypeOf(o))
for (let m of Object.getOwnPropertyNames(o))
if (((typeof handler[m]) === 'function') &&
KNOWN_METHODS.has(m))
methods.add(m);
}
return methods;
}
/**
* Set "Allow" header on the response.
*
* @private
* @param {module:x2node-ws~ServiceResponse} response The response.
* @param {Set.<string>} handlerMethods Methods supported by the handler.
*/
_setAllowedMethods(response, handlerMethods) {
const methodsArray = Array.from(handlerMethods);
methodsArray.push('OPTIONS');
if (handlerMethods.has('GET'))
methodsArray.push('HEAD');
response.addToMethodsListHeader('Allow', methodsArray);
}
} |
JavaScript | class Node {
constructor(val, next = null) {
this.data = val;
this.next = next;
}
} |
JavaScript | class AppInfoFilter extends models['Filter'] {
/**
* Create a AppInfoFilter.
* @member {array} [appInfo] An array containing all the required appInfo.
*/
constructor() {
super();
}
/**
* Defines the metadata of AppInfoFilter
*
* @returns {object} metadata of AppInfoFilter
*
*/
mapper() {
return {
required: false,
serializedName: 'app-info',
type: {
name: 'Composite',
className: 'AppInfoFilter',
modelProperties: {
type: {
required: true,
serializedName: 'type',
type: {
name: 'String'
}
},
appInfo: {
required: false,
serializedName: 'appInfo',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
}
}
}
};
}
} |
JavaScript | class CursorPlugin {
/**
* Cursor plugin definition factory
*
* This function must be used to create a plugin definition which can be
* used by wavesurfer to correctly instantiate the plugin.
*
* @param {CursorPluginParams} params parameters use to initialise the
* plugin
* @return {PluginDefinition} an object representing the plugin
*/
static create(params) {
return {
name: 'cursor',
deferInit: params && params.deferInit ? params.deferInit : false,
params: params,
staticProps: {
enableCursor() {
console.warn('Deprecated enableCursor!');
this.initPlugins('cursor');
}
},
instance: CursorPlugin
};
}
constructor(params, ws) {
this.wavesurfer = ws;
this.style = ws.util.style;
this._onDrawerCreated = () => {
this.drawer = this.wavesurfer.drawer;
this.wrapper = this.wavesurfer.drawer.wrapper;
this._onMousemove = e => this.updateCursorPosition(this.drawer.handleEvent(e));
this.wrapper.addEventListener('mousemove', this._onMousemove);
this._onMouseenter = () => this.showCursor();
this.wrapper.addEventListener('mouseenter', this._onMouseenter);
this._onMouseleave = () => this.hideCursor();
this.wrapper.addEventListener('mouseleave', this._onMouseleave);
this.cursor = this.wrapper.appendChild(
this.style(document.createElement('wave'), {
position: 'absolute',
zIndex: 3,
left: 0,
top: 0,
bottom: 0,
width: '0',
display: 'block',
borderRightStyle: 'solid',
borderRightWidth: 1 + 'px',
borderRightColor: 'black',
opacity: '.25',
pointerEvents: 'none'
})
);
};
}
init() {
// drawer already existed, just call initialisation code
if (this.wavesurfer.drawer) {
this._onDrawerCreated();
}
// the drawer was initialised, call the initialisation code
this.wavesurfer.on('drawer-created', this._onDrawerCreated);
}
destroy() {
this.wavesurfer.un('drawer-created', this._onDrawerCreated);
// if cursor was appended, remove it
if (this.cursor) {
this.cursor.parentNode.removeChild(this.cursor);
}
// if the drawer existed (the cached version referenced in the init code),
// remove the event listeners attached to it
if (this.drawer) {
this.wrapper.removeEventListener('mousemove', this._onMousemove);
this.wrapper.removeEventListener('mouseenter', this._onMouseenter);
this.wrapper.removeEventListener('mouseleave', this._onMouseleave);
}
}
updateCursorPosition(progress) {
const pos = Math.round(this.drawer.width * progress) / this.drawer.params.pixelRatio - 1;
this.style(this.cursor, {
left: `${pos}px`
});
}
showCursor() {
this.style(this.cursor, {
display: 'block'
});
}
hideCursor() {
this.style(this.cursor, {
display: 'none'
});
}
} |
JavaScript | class ArtifactPlugin {
constructor({ api }) {
this.api = api;
this.context = {};
this.enabled = false;
this.keepOnlyFailedTestsArtifacts = false;
this._disableReason = '';
}
get name() {
return this.constructor.name;
}
disable(reason) {
if (!this.enabled) {
return;
}
this.enabled = false;
this._disableReason = reason;
this._logDisableWarning();
}
/**
* Hook that is called inside device.launchApp() before
* the current app on the current device is relaunched.
*
* @protected
* @async
* @param {Object} event - Launch app event object
* @param {string} event.deviceId - Current deviceId
* @param {string} event.bundleId - Current bundleId
* @param {Object} event.launchArgs - Mutable key-value pairs of args before the launch
* @return {Promise<void>} - when done
*/
async onBeforeLaunchApp(event) {
Object.assign(this.context, {
bundleId: event.bundleId,
deviceId: event.deviceId,
launchArgs: event.launchArgs,
pid: NaN,
});
}
/**
* Hook that is called inside device.launchApp() and
* provides a new pid for the relaunched app for the
* artifacts that are dependent on pid.
*
* @protected
* @async
* @param {Object} event - Launch app event object
* @param {string} event.deviceId - Current deviceId
* @param {string} event.bundleId - Current bundleId
* @param {Object} event.launchArgs - key-value pairs of launch args
* @param {number} event.pid - Process id of the running app
* @return {Promise<void>} - when done
*/
async onLaunchApp(event) {
Object.assign(this.context, {
bundleId: event.bundleId,
deviceId: event.deviceId,
launchArgs: event.launchArgs,
pid: event.pid,
});
}
/**
* Hook that is supposed to be called from device.boot()
*
* @protected
* @async
* @param {Object} event - Device boot event object
* @param {string} event.deviceId - Current deviceId
* @param {boolean} event.coldBoot - true, if the device gets turned on from the shutdown state.
* @return {Promise<void>} - when done
*/
async onBootDevice(event) {
Object.assign(this.context, {
deviceId: event.deviceId,
bundleId: '',
pid: NaN,
});
}
/**
* Hook that is supposed to be called before app is terminated
*
* @protected
* @async
* @param {Object} event - App termination event object
* @param {string} event.deviceId - Current deviceId
* @param {string} event.bundleId - Current bundleId
* @return {Promise<void>} - when done
*/
async onBeforeTerminateApp(event) {
Object.assign(this.context, {
deviceId: event.deviceId,
bundleId: event.bundleId,
});
}
/**
* Hook that is supposed to be called before app is uninstalled
*
* @protected
* @async
* @param {Object} event - App uninstall event object
* @param {string} event.deviceId - Current deviceId
* @param {string} event.bundleId - Current bundleId
* @return {Promise<void>} - when done
*/
async onBeforeUninstallApp(event) {
Object.assign(this.context, {
deviceId: event.deviceId,
bundleId: event.bundleId,
});
}
/**
* Hook that is supposed to be called before device.shutdown() happens
*
* @protected
* @async
* @param {Object} event - Device shutdown event object
* @param {string} event.deviceId - Current deviceId
* @return {Promise<void>} - when done
*/
async onBeforeShutdownDevice(event) {
Object.assign(this.context, {
deviceId: event.deviceId,
});
}
/**
* Hook that is supposed to be called from device.shutdown()
*
* @protected
* @async
* @param {Object} event - Device shutdown event object
* @param {string} event.deviceId - Current deviceId
* @return {Promise<void>} - when done
*/
async onShutdownDevice(event) {
Object.assign(this.context, {
deviceId: event.deviceId,
bundleId: '',
pid: NaN,
});
}
/**
* Hook that is called on demand by some of user actions (e.g. device.takeScreeenshot())
*
* @protected
* @async
* @param {Object} event - User action event object
* @param {string} event.type - Action type
* @param {string} event.options - Action options
* @return {Promise<any>} - appropriate result of the action
*/
async onUserAction(event) {}
/**
* Hook that is called before any test begins
*
* @protected
* @async
* @return {Promise<void>} - when done
*/
async onBeforeAll() {
this.context.testSummary = null;
}
/**
* Hook that is called before a test begins
*
* @protected
* @async
* @param {TestSummary} testSummary - has name of currently running test
* @return {Promise<void>} - when done
*/
async onBeforeEach(testSummary) {
this.context.testSummary = testSummary;
}
/***
* @protected
* @async
* @param {TestSummary} testSummary - has name and status of test that ran
* @return {Promise<void>} - when done
*/
async onAfterEach(testSummary) {
this.context.testSummary = testSummary;
}
/**
* Hook that is called after all tests run
*
* @protected
* @async
* @return {Promise<void>} - when done
*/
async onAfterAll() {
this.context.testSummary = null;
this._logDisableWarning();
}
/**
* Hook that is called on SIGINT and SIGTERM
*
* @protected
* @async
* @return {Promise<void>} - when done
*/
async onTerminate() {
this.disable('it was terminated by SIGINT or SIGTERM');
this.onTerminate = _.noop;
this.onBootDevice = _.noop;
this.onBeforeShutdownDevice = _.noop;
this.onShutdownDevice = _.noop;
this.onBeforeTerminateApp = _.noop;
this.onBeforeLaunchApp = _.noop;
this.onLaunchApp = _.noop;
this.onUserAction = _.noop;
this.onBeforeAll = _.noop;
this.onBeforeEach = _.noop;
this.onAfterEach = _.noop;
this.onAfterAll = _.noop;
}
_logDisableWarning() {
if (!this.enabled && this._disableReason) {
log.warn({ event: 'PLUGIN_DISABLED' }, `Artifact plugin ${this.constructor.name} was disabled because ${this._disableReason}`);
}
}
shouldKeepArtifactOfTest(testSummary) {
if (this.keepOnlyFailedTestsArtifacts && testSummary.status !== 'failed') {
return false;
}
return true;
}
} |
JavaScript | class Command {
constructor(sourceDSU) {
this.sourceDSU = sourceDSU;
}
/**
* Executes the command
* @param {Archive} bar
* @param {string} command
* @param {string[]} next
* @param {object} [options]
* @param {function(err)} callback
*/
execute(bar, command, next, options, callback){
const args = this._parseCommand(command, next);
this._runCommand(bar, args, options, callback)
}
/**
* @param {string} command the command without it's name
* @param {string[]} next the following Commands
* @private
*/
_parseCommand(command, next){
throw new Error("No parsing logic defined");
}
/**
* @param {Archive} bar
* @param {string} command the command without it's name
* @param {string|object} arg the command argument
* @param {object} options
* @param {function(err)} callback
* @private
*/
_runCommand(bar, arg, options, callback){
throw new Error("No parsing logic defined");
}
/**
* @return the operation name
*/
getOperationName(){
throw new Error('No name defined');
}
} |
JavaScript | class Logout {
constructor(authService) {
this.authService = authService;
}
activate() {
// When we get to the logout route, the logout
// method on the auth service will be called
// and we will be redirected to the login view
this.authService.logout('#/login')
.then(response => {
console.log('Logged Out');
})
.catch(err => {
console.log('Error Logging Out');
});
}
} |
JavaScript | class ShellBarItem extends UI5Element {
static get metadata() {
return metadata;
}
static get render() {
return litRender;
}
static get template() {
return ShellBarItemTemplate;
}
} |
JavaScript | class TextureCache {
/**
* @ignore
*/
constructor(max_size) {
this.cache = new Map();
this.tinted = new Map();
this.units = new Map();
this.max_size = max_size || Infinity;
this.clear();
}
/**
* @ignore
*/
clear() {
this.cache.clear();
this.tinted.clear();
this.units.clear();
this.length = 0;
}
/**
* @ignore
*/
validate() {
if (this.length >= this.max_size) {
// TODO: Merge textures instead of throwing an exception
throw new Error(
"Texture cache overflow: " + this.max_size +
" texture units available for this GPU."
);
}
}
/**
* @ignore
*/
get(image, atlas) {
if (!this.cache.has(image)) {
if (!atlas) {
atlas = createAtlas(image.width, image.height, image.src ? fileUtil.getBasename(image.src) : undefined);
}
this.set(image, new Texture(atlas, image, false));
}
return this.cache.get(image);
}
/**
* @ignore
*/
tint(src, color) {
// make sure the src is in the cache
var image_cache = this.tinted.get(src);
if (image_cache === undefined) {
image_cache = this.tinted.set(src, new Map());
}
if (!image_cache.has(color)) {
image_cache.set(color, renderer.tint(src, color, "multiply"));
}
return image_cache.get(color);
}
/**
* @ignore
*/
set(image, texture) {
var width = image.width;
var height = image.height;
// warn if a non POT texture is added to the cache when using WebGL1
if (renderer.WebGLVersion === 1 && (!isPowerOfTwo(width) || !isPowerOfTwo(height))) {
var src = typeof image.src !== "undefined" ? image.src : image;
console.warn(
"[Texture] " + src + " is not a POT texture " +
"(" + width + "x" + height + ")"
);
}
this.cache.set(image, texture);
}
/**
* @ignore
*/
getUnit(texture) {
if (!this.units.has(texture)) {
this.validate();
this.units.set(texture, this.length++);
}
return this.units.get(texture);
}
} |
JavaScript | class Popup extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Display the popup without the pointing arrow. */
basic: PropTypes.bool,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Simple text content for the popover. */
content: customPropTypes.itemShorthand,
/** A flowing Popup has no maximum width and continues to flow to fit its content. */
flowing: PropTypes.bool,
/** Takes up the entire width of its offset container. */
// TODO: implement the Popup fluid layout
// fluid: PropTypes.bool,
/** Header displayed above the content in bold. */
header: customPropTypes.itemShorthand,
/** Hide the Popup when scrolling the window. */
hideOnScroll: PropTypes.bool,
/** Whether the popup should not close on hover. */
hoverable: PropTypes.bool,
/** Invert the colors of the Popup. */
inverted: PropTypes.bool,
/** Horizontal offset in pixels to be applied to the Popup. */
offset: PropTypes.number,
/** Events triggering the popup. */
on: PropTypes.oneOfType([
PropTypes.oneOf(['hover', 'click', 'focus']),
PropTypes.arrayOf(PropTypes.oneOf(['hover', 'click', 'focus'])),
]),
/**
* Called when a close event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClose: PropTypes.func,
/**
* Called when the portal is mounted on the DOM.
*
* @param {null}
* @param {object} data - All props.
*/
onMount: PropTypes.func,
/**
* Called when an open event happens.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onOpen: PropTypes.func,
/**
* Called when the portal is unmounted from the DOM.
*
* @param {null}
* @param {object} data - All props.
*/
onUnmount: PropTypes.func,
/** Position for the popover. */
position: PropTypes.oneOf(POSITIONS),
/** Popup size. */
size: PropTypes.oneOf(_.without(SUI.SIZES, 'medium', 'big', 'massive')),
/** Custom Popup style. */
style: PropTypes.object,
/** Element to be rendered in-place where the popup is defined. */
trigger: PropTypes.node,
/** Popup width. */
wide: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(['very']),
]),
}
static defaultProps = {
position: 'top left',
on: 'hover',
}
static _meta = {
name: 'Popup',
type: META.TYPES.MODULE,
}
static Content = PopupContent
static Header = PopupHeader
state = {}
computePopupStyle(positions) {
const style = { position: 'absolute' }
// Do not access window/document when server side rendering
if (!isBrowser()) return style
const { offset } = this.props
const { pageYOffset, pageXOffset } = window
const { clientWidth, clientHeight } = document.documentElement
if (_.includes(positions, 'right')) {
style.right = Math.round(clientWidth - (this.coords.right + pageXOffset))
style.left = 'auto'
} else if (_.includes(positions, 'left')) {
style.left = Math.round(this.coords.left + pageXOffset)
style.right = 'auto'
} else { // if not left nor right, we are horizontally centering the element
const xOffset = (this.coords.width - this.popupCoords.width) / 2
style.left = Math.round(this.coords.left + xOffset + pageXOffset)
style.right = 'auto'
}
if (_.includes(positions, 'top')) {
style.bottom = Math.round(clientHeight - (this.coords.top + pageYOffset))
style.top = 'auto'
} else if (_.includes(positions, 'bottom')) {
style.top = Math.round(this.coords.bottom + pageYOffset)
style.bottom = 'auto'
} else { // if not top nor bottom, we are vertically centering the element
const yOffset = (this.coords.height + this.popupCoords.height) / 2
style.top = Math.round((this.coords.bottom + pageYOffset) - yOffset)
style.bottom = 'auto'
const xOffset = this.popupCoords.width + 8
if (_.includes(positions, 'right')) {
style.right -= xOffset
} else {
style.left -= xOffset
}
}
if (offset) {
if (_.isNumber(style.right)) {
style.right -= offset
} else {
style.left -= offset
}
}
return style
}
// check if the style would display
// the popup outside of the view port
isStyleInViewport(style) {
const { pageYOffset, pageXOffset } = window
const { clientWidth, clientHeight } = document.documentElement
const element = {
top: style.top,
left: style.left,
width: this.popupCoords.width,
height: this.popupCoords.height,
}
if (_.isNumber(style.right)) {
element.left = clientWidth - style.right - element.width
}
if (_.isNumber(style.bottom)) {
element.top = clientHeight - style.bottom - element.height
}
// hidden on top
if (element.top < pageYOffset) return false
// hidden on the bottom
if (element.top + element.height > pageYOffset + clientHeight) return false
// hidden the left
if (element.left < pageXOffset) return false
// hidden on the right
if (element.left + element.width > pageXOffset + clientWidth) return false
return true
}
setPopupStyle() {
if (!this.coords || !this.popupCoords) return
let position = this.props.position
let style = this.computePopupStyle(position)
// Lets detect if the popup is out of the viewport and adjust
// the position accordingly
const positions = _.without(POSITIONS, position).concat([position])
for (let i = 0; !this.isStyleInViewport(style) && i < positions.length; i += 1) {
style = this.computePopupStyle(positions[i])
position = positions[i]
}
// Append 'px' to every numerical values in the style
style = _.mapValues(style, value => (_.isNumber(value) ? `${value}px` : value))
this.setState({ style, position })
}
getPortalProps() {
const portalProps = {}
const { on, hoverable } = this.props
const normalizedOn = _.isArray(on) ? on : [on]
if (hoverable) {
portalProps.closeOnPortalMouseLeave = true
portalProps.mouseLeaveDelay = 300
}
if (_.includes(normalizedOn, 'click')) {
portalProps.openOnTriggerClick = true
portalProps.closeOnTriggerClick = true
portalProps.closeOnDocumentClick = true
}
if (_.includes(normalizedOn, 'focus')) {
portalProps.openOnTriggerFocus = true
portalProps.closeOnTriggerBlur = true
}
if (_.includes(normalizedOn, 'hover')) {
portalProps.openOnTriggerMouseEnter = true
portalProps.closeOnTriggerMouseLeave = true
// Taken from SUI: https://git.io/vPmCm
portalProps.mouseLeaveDelay = 70
portalProps.mouseEnterDelay = 50
}
return portalProps
}
hideOnScroll = (e) => {
this.setState({ closed: true })
eventStack.unsub('scroll', this.hideOnScroll, { target: window })
setTimeout(() => this.setState({ closed: false }), 50)
this.handleClose(e)
}
handleClose = (e) => {
debug('handleClose()')
_.invoke(this.props, 'onClose', e, this.props)
}
handleOpen = (e) => {
debug('handleOpen()')
this.coords = e.currentTarget.getBoundingClientRect()
const { onOpen } = this.props
if (onOpen) onOpen(e, this.props)
}
handlePortalMount = (e) => {
debug('handlePortalMount()')
const { hideOnScroll } = this.props
if (hideOnScroll) eventStack.sub('scroll', this.hideOnScroll, { target: window })
_.invoke(this.props, 'onMount', e, this.props)
}
handlePortalUnmount = (e) => {
debug('handlePortalUnmount()')
const { hideOnScroll } = this.props
if (hideOnScroll) eventStack.unsub('scroll', this.hideOnScroll, { target: window })
_.invoke(this.props, 'onUnmount', e, this.props)
}
handlePopupRef = (popupRef) => {
debug('popupMounted()')
this.popupCoords = popupRef ? popupRef.getBoundingClientRect() : null
this.setPopupStyle()
}
render() {
const {
basic,
children,
className,
content,
flowing,
header,
inverted,
size,
trigger,
wide,
} = this.props
const { position, closed } = this.state
const style = _.assign({}, this.state.style, this.props.style)
const classes = cx(
'ui',
position,
size,
useKeyOrValueAndKey(wide, 'wide'),
useKeyOnly(basic, 'basic'),
useKeyOnly(flowing, 'flowing'),
useKeyOnly(inverted, 'inverted'),
'popup transition visible',
className,
)
if (closed) return trigger
const unhandled = getUnhandledProps(Popup, this.props)
const portalPropNames = Portal.handledProps
const rest = _.reduce(unhandled, (acc, val, key) => {
if (!_.includes(portalPropNames, key)) acc[key] = val
return acc
}, {})
const portalProps = _.pick(unhandled, portalPropNames)
const ElementType = getElementType(Popup, this.props)
const popupJSX = (
<ElementType {...rest} className={classes} style={style} ref={this.handlePopupRef}>
{children}
{childrenUtils.isNil(children) && PopupHeader.create(header)}
{childrenUtils.isNil(children) && PopupContent.create(content)}
</ElementType>
)
const mergedPortalProps = { ...this.getPortalProps(), ...portalProps }
debug('portal props:', mergedPortalProps)
return (
<Portal
{...mergedPortalProps}
trigger={trigger}
onClose={this.handleClose}
onMount={this.handlePortalMount}
onOpen={this.handleOpen}
onUnmount={this.handlePortalUnmount}
>
{popupJSX}
</Portal>
)
}
} |
JavaScript | class HtmlMediaSource extends videojs.EventTarget {
constructor() {
super();
let property;
this.nativeMediaSource_ = new window.MediaSource();
// delegate to the native MediaSource's methods by default
for (property in this.nativeMediaSource_) {
if (!(property in HtmlMediaSource.prototype) &&
typeof this.nativeMediaSource_[property] === 'function') {
this[property] = this.nativeMediaSource_[property].bind(this.nativeMediaSource_);
}
}
// emulate `duration` and `seekable` until seeking can be
// handled uniformly for live streams
// see https://github.com/w3c/media-source/issues/5
this.duration_ = NaN;
Object.defineProperty(this, 'duration', {
get() {
if (this.duration_ === Infinity) {
return this.duration_;
}
return this.nativeMediaSource_.duration;
},
set(duration) {
this.duration_ = duration;
if (duration !== Infinity) {
this.nativeMediaSource_.duration = duration;
return;
}
}
});
Object.defineProperty(this, 'seekable', {
get() {
if (this.duration_ === Infinity) {
return videojs.createTimeRanges([[0, this.nativeMediaSource_.duration]]);
}
return this.nativeMediaSource_.seekable;
}
});
Object.defineProperty(this, 'readyState', {
get() {
return this.nativeMediaSource_.readyState;
}
});
Object.defineProperty(this, 'activeSourceBuffers', {
get() {
return this.activeSourceBuffers_;
}
});
// the list of virtual and native SourceBuffers created by this
// MediaSource
this.sourceBuffers = [];
this.activeSourceBuffers_ = [];
/**
* update the list of active source buffers based upon various
* imformation from HLS and video.js
*
* @private
*/
this.updateActiveSourceBuffers_ = () => {
// Retain the reference but empty the array
this.activeSourceBuffers_.length = 0;
// If there is only one source buffer, then it will always be active and audio will
// be disabled based on the codec of the source buffer
if (this.sourceBuffers.length === 1) {
let sourceBuffer = this.sourceBuffers[0];
sourceBuffer.appendAudioInitSegment_ = true;
sourceBuffer.audioDisabled_ = !sourceBuffer.audioCodec_;
this.activeSourceBuffers_.push(sourceBuffer);
return;
}
// There are 2 source buffers, a combined (possibly video only) source buffer and
// and an audio only source buffer.
// By default, the audio in the combined virtual source buffer is enabled
// and the audio-only source buffer (if it exists) is disabled.
let disableCombined = false;
let disableAudioOnly = true;
// TODO: maybe we can store the sourcebuffers on the track objects?
// safari may do something like this
for (let i = 0; i < this.player_.audioTracks().length; i++) {
let track = this.player_.audioTracks()[i];
if (track.enabled && track.kind !== 'main') {
// The enabled track is an alternate audio track so disable the audio in
// the combined source buffer and enable the audio-only source buffer.
disableCombined = true;
disableAudioOnly = false;
break;
}
}
this.sourceBuffers.forEach((sourceBuffer, index) => {
/* eslinst-disable */
// TODO once codecs are required, we can switch to using the codecs to determine
// what stream is the video stream, rather than relying on videoTracks
/* eslinst-enable */
sourceBuffer.appendAudioInitSegment_ = true;
if (sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
// combined
sourceBuffer.audioDisabled_ = disableCombined;
} else if (sourceBuffer.videoCodec_ && !sourceBuffer.audioCodec_) {
// If the "combined" source buffer is video only, then we do not want
// disable the audio-only source buffer (this is mostly for demuxed
// audio and video hls)
sourceBuffer.audioDisabled_ = true;
disableAudioOnly = false;
} else if (!sourceBuffer.videoCodec_ && sourceBuffer.audioCodec_) {
// audio only
// In the case of audio only with alternate audio and disableAudioOnly is true
// this means we want to disable the audio on the alternate audio sourcebuffer
// but not the main "combined" source buffer. The "combined" source buffer is
// always at index 0, so this ensures audio won't be disabled in both source
// buffers.
sourceBuffer.audioDisabled_ = index ? disableAudioOnly : !disableAudioOnly;
if (sourceBuffer.audioDisabled_) {
return;
}
}
this.activeSourceBuffers_.push(sourceBuffer);
});
};
this.onPlayerMediachange_ = () => {
this.sourceBuffers.forEach((sourceBuffer) => {
sourceBuffer.appendAudioInitSegment_ = true;
});
};
this.onHlsReset_ = () => {
this.sourceBuffers.forEach((sourceBuffer) => {
if (sourceBuffer.transmuxer_) {
sourceBuffer.transmuxer_.postMessage({action: 'resetCaptions'});
}
});
};
this.onHlsSegmentTimeMapping_ = (event) => {
this.sourceBuffers.forEach(buffer => buffer.timeMapping_ = event.mapping);
};
// Re-emit MediaSource events on the polyfill
[
'sourceopen',
'sourceclose',
'sourceended'
].forEach(function(eventName) {
this.nativeMediaSource_.addEventListener(eventName, this.trigger.bind(this));
}, this);
// capture the associated player when the MediaSource is
// successfully attached
this.on('sourceopen', (event) => {
// Get the player this MediaSource is attached to
let video = document.querySelector('[src="' + this.url_ + '"]');
if (!video) {
return;
}
this.player_ = videojs(video.parentNode);
if (!this.player_) {
return;
}
// hls-reset is fired by videojs.Hls on to the tech after the main SegmentLoader
// resets its state and flushes the buffer
this.player_.tech_.on('hls-reset', this.onHlsReset_);
// hls-segment-time-mapping is fired by videojs.Hls on to the tech after the main
// SegmentLoader inspects an MTS segment and has an accurate stream to display
// time mapping
this.player_.tech_.on('hls-segment-time-mapping', this.onHlsSegmentTimeMapping_);
if (this.player_.audioTracks && this.player_.audioTracks()) {
this.player_.audioTracks().on('change', this.updateActiveSourceBuffers_);
this.player_.audioTracks().on('addtrack', this.updateActiveSourceBuffers_);
this.player_.audioTracks().on('removetrack', this.updateActiveSourceBuffers_);
}
this.player_.on('mediachange', this.onPlayerMediachange_);
});
this.on('sourceended', (event) => {
let duration = durationOfVideo(this.duration);
for (let i = 0; i < this.sourceBuffers.length; i++) {
let sourcebuffer = this.sourceBuffers[i];
let cues = sourcebuffer.metadataTrack_ && sourcebuffer.metadataTrack_.cues;
if (cues && cues.length) {
cues[cues.length - 1].endTime = duration;
}
}
});
// explicitly terminate any WebWorkers that were created
// by SourceHandlers
this.on('sourceclose', function(event) {
this.sourceBuffers.forEach(function(sourceBuffer) {
if (sourceBuffer.transmuxer_) {
sourceBuffer.transmuxer_.terminate();
}
});
this.sourceBuffers.length = 0;
if (!this.player_) {
return;
}
if (this.player_.audioTracks && this.player_.audioTracks()) {
this.player_.audioTracks().off('change', this.updateActiveSourceBuffers_);
this.player_.audioTracks().off('addtrack', this.updateActiveSourceBuffers_);
this.player_.audioTracks().off('removetrack', this.updateActiveSourceBuffers_);
}
// We can only change this if the player hasn't been disposed of yet
// because `off` eventually tries to use the el_ property. If it has
// been disposed of, then don't worry about it because there are no
// event handlers left to unbind anyway
if (this.player_.el_) {
this.player_.off('mediachange', this.onPlayerMediachange_);
}
if (this.player_.tech_ && this.player_.tech_.el_) {
this.player_.tech_.off('hls-reset', this.onHlsReset_);
this.player_.tech_.off('hls-segment-time-mapping', this.onHlsSegmentTimeMapping_);
}
});
}
/**
* Add a range that that can now be seeked to.
*
* @param {Double} start where to start the addition
* @param {Double} end where to end the addition
* @private
*/
addSeekableRange_(start, end) {
let error;
if (this.duration !== Infinity) {
error = new Error('MediaSource.addSeekableRange() can only be invoked ' +
'when the duration is Infinity');
error.name = 'InvalidStateError';
error.code = 11;
throw error;
}
if (end > this.nativeMediaSource_.duration ||
isNaN(this.nativeMediaSource_.duration)) {
this.nativeMediaSource_.duration = end;
}
}
/**
* Add a source buffer to the media source.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer
* @param {String} type the content-type of the content
* @return {Object} the created source buffer
*/
addSourceBuffer(type) {
let buffer;
let parsedType = parseContentType(type);
// Create a VirtualSourceBuffer to transmux MPEG-2 transport
// stream segments into fragmented MP4s
if ((/^(video|audio)\/mp2t$/i).test(parsedType.type)) {
let codecs = [];
if (parsedType.parameters && parsedType.parameters.codecs) {
codecs = parsedType.parameters.codecs.split(',');
codecs = translateLegacyCodecs(codecs);
codecs = codecs.filter((codec) => {
return (isAudioCodec(codec) || isVideoCodec(codec));
});
}
if (codecs.length === 0) {
codecs = ['avc1.4d400d', 'mp4a.40.2'];
}
buffer = new VirtualSourceBuffer(this, codecs);
if (this.sourceBuffers.length !== 0) {
// If another VirtualSourceBuffer already exists, then we are creating a
// SourceBuffer for an alternate audio track and therefore we know that
// the source has both an audio and video track.
// That means we should trigger the manual creation of the real
// SourceBuffers instead of waiting for the transmuxer to return data
this.sourceBuffers[0].createRealSourceBuffers_();
buffer.createRealSourceBuffers_();
// Automatically disable the audio on the first source buffer if
// a second source buffer is ever created
this.sourceBuffers[0].audioDisabled_ = true;
}
} else {
// delegate to the native implementation
buffer = this.nativeMediaSource_.addSourceBuffer(type);
}
this.sourceBuffers.push(buffer);
return buffer;
}
} |
JavaScript | class MotionTracker extends EventTarget {
constructor() {
super();
// Init class parameters
this.deviceIsMoving = null;
this.lastChange = new Date(new Date().getTime - DEBOUNCE_INTERVAL);
// Bind methods
this.handleTick = this.handleTick.bind(this);
// Bind event listener for device motion
window.addEventListener('devicemotion', this.handleTick);
}
/**
* Handle an acceleration tick from the Device Motion API
*
* @param {DeviceMotionEvent} event
*/
handleTick(event) {
if (this.lastChange.getTime() + DEBOUNCE_INTERVAL > new Date().getTime()) {
return;
}
// Calculate the total sum of the accelaration on the device
const sumAcceleration = Math.abs(event.acceleration.x) + Math.abs(event.acceleration.y) + Math.abs(event.acceleration.z);
// if (new Date().getTime() % 1000 < 20) {
// console.log(sumAcceleration);
// }
// If the device is not moving and the sum of accelerations exceeds the threshold, we consider the device to be moving
if (!this.deviceIsMoving && sumAcceleration > MOVEMENT_THRESHOLD.start) {
this.deviceIsMoving = true;
this.lastChange = new Date();
this.dispatchEvent(deviceStartedMovingEvent);
// If the device is moving and the sum of accelerations drops below the threshold, we consider the device to be still
} else if (this.deviceIsMoving && sumAcceleration < MOVEMENT_THRESHOLD.stop) {
this.deviceIsMoving = false;
this.lastChange = new Date();
this.dispatchEvent(deviceStoppedMovingEvent);
}
}
} |
JavaScript | class RestrictedEditingModeEditing extends Plugin {
/**
* @inheritDoc
*/
static get pluginName() {
return 'RestrictedEditingModeEditing';
}
/**
* @inheritDoc
*/
constructor( editor ) {
super( editor );
editor.config.define( 'restrictedEditing', {
allowedCommands: [ 'bold', 'italic', 'link', 'unlink' ],
allowedAttributes: [ 'bold', 'italic', 'linkHref' ]
} );
/**
* Command names that are enabled outside the non-restricted regions.
*
* @type {Set.<String>}
* @private
*/
this._alwaysEnabled = new Set( [ 'undo', 'redo', 'goToPreviousRestrictedEditingException', 'goToNextRestrictedEditingException' ] );
/**
* Commands allowed in non-restricted areas.
*
* Commands always enabled combine typing feature commands: `'typing'`, `'delete'` and `'forwardDelete'` with commands defined
* in the feature configuration.
*
* @type {Set<string>}
* @private
*/
this._allowedInException = new Set( [ 'input', 'delete', 'forwardDelete' ] );
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const editingView = editor.editing.view;
const allowedCommands = editor.config.get( 'restrictedEditing.allowedCommands' );
allowedCommands.forEach( commandName => this._allowedInException.add( commandName ) );
this._setupConversion();
this._setupCommandsToggling();
this._setupRestrictions();
// Commands & keystrokes that allow navigation in the content.
editor.commands.add( 'goToPreviousRestrictedEditingException', new RestrictedEditingNavigationCommand( editor, 'backward' ) );
editor.commands.add( 'goToNextRestrictedEditingException', new RestrictedEditingNavigationCommand( editor, 'forward' ) );
editor.keystrokes.set( 'Tab', getCommandExecuter( editor, 'goToNextRestrictedEditingException' ) );
editor.keystrokes.set( 'Shift+Tab', getCommandExecuter( editor, 'goToPreviousRestrictedEditingException' ) );
editor.keystrokes.set( 'Ctrl+A', getSelectAllHandler( editor ) );
editingView.change( writer => {
for ( const root of editingView.document.roots ) {
writer.addClass( 'ck-restricted-editing_mode_restricted', root );
}
} );
}
/**
* Makes the given command always enabled in the restricted editing mode (regardless
* of selection location).
*
* To enable some commands in non-restricted areas of the content use
* {@link module:restricted-editing/restrictededitingmode~RestrictedEditingModeConfig#allowedCommands} configuration option.
*
* @param {String} commandName Name of the command to enable.
*/
enableCommand( commandName ) {
const command = this.editor.commands.get( commandName );
command.clearForceDisabled( COMMAND_FORCE_DISABLE_ID );
this._alwaysEnabled.add( commandName );
}
/**
* Sets up the restricted mode editing conversion:
*
* * ucpast & downcast converters,
* * marker highlighting in the edting area,
* * marker post-fixers.
*
* @private
*/
_setupConversion() {
const editor = this.editor;
const model = editor.model;
const doc = model.document;
// The restricted editing does not attach additional data to the zones so there's no need for smarter markers management.
// Also, the markers will only be created when when loading the data.
let markerNumber = 0;
editor.conversion.for( 'upcast' ).add( upcastHighlightToMarker( {
view: {
name: 'span',
classes: 'restricted-editing-exception'
},
model: () => {
markerNumber++; // Starting from restrictedEditingException:1 marker.
return `restrictedEditingException:${ markerNumber }`;
}
} ) );
// Currently the marker helpers are tied to other use-cases and do not render collapsed marker as highlight.
// That's why there are 2 downcast converters for them:
// 1. The default marker-to-highlight will wrap selected text with `<span>`.
editor.conversion.for( 'downcast' ).markerToHighlight( {
model: 'restrictedEditingException',
// Use callback to return new object every time new marker instance is created - otherwise it will be seen as the same marker.
view: () => {
return {
name: 'span',
classes: 'restricted-editing-exception',
priority: -10
};
}
} );
// 2. But for collapsed marker we need to render it as an element.
// Additionally the editing pipeline should always display a collapsed markers.
editor.conversion.for( 'editingDowncast' ).markerToElement( {
model: 'restrictedEditingException',
view: ( markerData, viewWriter ) => {
return viewWriter.createUIElement( 'span', {
class: 'restricted-editing-exception restricted-editing-exception_collapsed'
} );
}
} );
editor.conversion.for( 'dataDowncast' ).markerToElement( {
model: 'restrictedEditingException',
view: ( markerData, viewWriter ) => {
return viewWriter.createEmptyElement( 'span', {
class: 'restricted-editing-exception'
} );
}
} );
doc.registerPostFixer( extendMarkerOnTypingPostFixer( editor ) );
doc.registerPostFixer( resurrectCollapsedMarkerPostFixer( editor ) );
model.markers.on( 'update:restrictedEditingException', ensureNewMarkerIsFlat( editor ) );
setupExceptionHighlighting( editor );
}
/**
* Setups additional editing restrictions beyond command toggling:
*
* * delete content range trimming
* * disabling input command outside exception marker
* * restricting clipboard holder to text only
* * restricting text attributes in content
*
* @private
*/
_setupRestrictions() {
const editor = this.editor;
const model = editor.model;
const selection = model.document.selection;
const viewDoc = editor.editing.view.document;
this.listenTo( model, 'deleteContent', restrictDeleteContent( editor ), { priority: 'high' } );
const inputCommand = editor.commands.get( 'input' );
// The restricted editing might be configured without input support - ie allow only bolding or removing text.
// This check is bit synthetic since only tests are used this way.
if ( inputCommand ) {
this.listenTo( inputCommand, 'execute', disallowInputExecForWrongRange( editor ), { priority: 'high' } );
}
// Block clipboard outside exception marker on paste.
this.listenTo( viewDoc, 'clipboardInput', function( evt ) {
if ( !isRangeInsideSingleMarker( editor, selection.getFirstRange() ) ) {
evt.stop();
}
}, { priority: 'high' } );
// Block clipboard outside exception marker on cut.
this.listenTo( viewDoc, 'clipboardOutput', ( evt, data ) => {
if ( data.method == 'cut' && !isRangeInsideSingleMarker( editor, selection.getFirstRange() ) ) {
evt.stop();
}
}, { priority: 'high' } );
const allowedAttributes = editor.config.get( 'restrictedEditing.allowedAttributes' );
model.schema.addAttributeCheck( onlyAllowAttributesFromList( allowedAttributes ) );
model.schema.addChildCheck( allowTextOnlyInClipboardHolder );
}
/**
* Sets up the command toggling which enables or disables commands based on the user selection.
*
* @private
*/
_setupCommandsToggling() {
const editor = this.editor;
const model = editor.model;
const doc = model.document;
this._disableCommands( editor );
this.listenTo( doc.selection, 'change', this._checkCommands.bind( this ) );
this.listenTo( doc, 'change:data', this._checkCommands.bind( this ) );
}
/**
* Checks if commands should be enabled or disabled based on the current selection.
*
* @private
*/
_checkCommands() {
const editor = this.editor;
const selection = editor.model.document.selection;
if ( selection.rangeCount > 1 ) {
this._disableCommands( editor );
return;
}
const marker = getMarkerAtPosition( editor, selection.focus );
this._disableCommands();
if ( isSelectionInMarker( selection, marker ) ) {
this._enableCommands( marker );
}
}
/**
* Enables commands in non-restricted regions.
*
* @returns {module:engine/model/markercollection~Marker} marker
* @private
*/
_enableCommands( marker ) {
const editor = this.editor;
const commands = this._getCommandNamesToToggle( editor, this._allowedInException )
.filter( name => this._allowedInException.has( name ) )
.filter( filterDeleteCommandsOnMarkerBoundaries( editor.model.document.selection, marker.getRange() ) )
.map( name => editor.commands.get( name ) );
for ( const command of commands ) {
command.clearForceDisabled( COMMAND_FORCE_DISABLE_ID );
}
}
/**
* Disables commands outside non-restricted regions.
*
* @private
*/
_disableCommands() {
const editor = this.editor;
const commands = this._getCommandNamesToToggle( editor )
.map( name => editor.commands.get( name ) );
for ( const command of commands ) {
command.forceDisabled( COMMAND_FORCE_DISABLE_ID );
}
}
/**
* Returns command names that should be toggleable.
*
* @param {module:core/editor/editor~Editor} editor
* @returns {Array.<String>}
* @private
*/
_getCommandNamesToToggle( editor ) {
return Array.from( editor.commands.names() )
.filter( name => !this._alwaysEnabled.has( name ) );
}
} |
JavaScript | class Command extends AliasPiece {
/**
* @typedef {AliasPieceOptions} CommandOptions
* @property {boolean} [autoAliases=true] If automatic aliases should be added (adds aliases of name and aliases without dashes)
* @property {external:PermissionResolvable} [requiredPermissions=0] The required Discord permissions for the bot to use this command
* @property {number} [bucket=1] The number of times this command can be run before ratelimited by the cooldown
* @property {number} [cooldown=0] The amount of time before the user can run the command again in seconds
* @property {string} [cooldownLevel='author'] The level the cooldown applies to (valid options are 'author', 'channel', 'guild')
* @property {boolean} [deletable=false] If the responses should be deleted if the triggering message is deleted
* @property {(string|Function)} [description=''] The help description for the command
* @property {(string|Function)} [extendedHelp=language.get('COMMAND_HELP_NO_EXTENDED')] Extended help strings
* @property {boolean} [guarded=false] If the command can be disabled on a guild level (does not effect global disable)
* @property {boolean} [nsfw=false] If the command should only run in nsfw channels
* @property {number} [permissionLevel=0] The required permission level to use the command
* @property {number} [promptLimit=0] The number or attempts allowed for re-prompting an argument
* @property {number} [promptTime=30000] The time allowed for re-prompting of this command
* @property {boolean} [quotedStringSupport=false] Whether args for this command should not deliminated inside quotes
* @property {string[]} [requiredSettings=[]] The required guild settings to use this command
* @property {string[]} [runIn=['text','dm']] What channel types the command should run in
* @property {boolean} [subcommands=false] Whether to enable sub commands or not
* @property {string} [usage=''] The usage string for the command
* @property {?string} [usageDelim=undefined] The string to delimit the command input for usage
*/
/**
* @since 0.0.1
* @param {KlasaClient} client The Klasa Client
* @param {CommandStore} store The Command store
* @param {Array} file The path from the pieces folder to the command file
* @param {string} directory The base directory to the pieces folder
* @param {CommandOptions} [options={}] Optional Command settings
*/
constructor(client, store, file, directory, options = {}) {
super(client, store, file, directory, options);
this.name = this.name.toLowerCase();
if (options.autoAliases) {
if (this.name.includes('-')) this.aliases.push(this.name.replace(/-/g, ''));
for (const alias of this.aliases) if (alias.includes('-')) this.aliases.push(alias.replace(/-/g, ''));
}
/**
* The required bot permissions to run this command
* @since 0.0.1
* @type {external:Permissions}
*/
this.requiredPermissions = new Permissions(options.requiredPermissions).freeze();
/**
* Whether this command should have it's responses deleted if the triggering message is deleted
* @since 0.5.0
* @type {boolean}
*/
this.deletable = options.deletable;
/**
* The description of the command
* @since 0.0.1
* @type {(string|Function)}
* @param {Language} language The language for the description
* @returns {string}
*/
this.description = isFunction(options.description) ?
(language = this.client.languages.default) => options.description(language) :
options.description;
/**
* The extended help for the command
* @since 0.0.1
* @type {(string|Function)}
* @param {Language} language The language for the extended help
* @returns {string}
*/
this.extendedHelp = isFunction(options.extendedHelp) ?
(language = this.client.languages.default) => options.extendedHelp(language) :
options.extendedHelp;
/**
* The full category for the command
* @since 0.0.1
* @type {string[]}
*/
this.fullCategory = file.slice(0, -1);
/**
* Whether this command should not be able to be disabled in a guild or not
* @since 0.5.0
* @type {boolean}
*/
this.guarded = options.guarded;
/**
* Whether this command should only run in NSFW channels or not
* @since 0.5.0
* @type {boolean}
*/
this.nsfw = options.nsfw;
/**
* The required permissionLevel to run this command
* @since 0.0.1
* @type {number}
*/
this.permissionLevel = options.permissionLevel;
/**
* The number or attempts allowed for re-prompting an argument
* @since 0.5.0
* @type {number}
*/
this.promptLimit = options.promptLimit;
/**
* The time allowed for re-prompting of this command
* @since 0.5.0
* @type {number}
*/
this.promptTime = options.promptTime;
/**
* Whether to use quoted string support for this command or not
* @since 0.2.1
* @type {boolean}
*/
this.quotedStringSupport = options.quotedStringSupport;
/**
* The required per guild settings to run this command
* @since 0.0.1
* @type {string[]}
*/
this.requiredSettings = options.requiredSettings;
/**
* What channels the command should run in
* @since 0.0.1
* @type {string[]}
*/
this.runIn = options.runIn;
/**
* Whether to enable subcommands or not
* @since 0.5.0
* @type {boolean}
*/
this.subcommands = options.subcommands;
/**
* The parsed usage for the command
* @since 0.0.1
* @type {CommandUsage}
*/
this.usage = new CommandUsage(client, options.usage, options.usageDelim, this);
/**
* The level at which cooldowns should apply
* @since 0.5.0
* @type {string}
*/
this.cooldownLevel = options.cooldownLevel;
if (!['author', 'channel', 'guild'].includes(this.cooldownLevel)) throw new Error('Invalid cooldownLevel');
/**
* Any active cooldowns for the command
* @since 0.0.1
* @type {RateLimitManager}
* @private
*/
this.cooldowns = new RateLimitManager(options.bucket, options.cooldown * 1000);
}
/**
* The number of times this command can be run before ratelimited by the cooldown
* @since 0.5.0
* @type {number}
* @readonly
*/
get bucket() {
return this.cooldowns.bucket;
}
/**
* The cooldown in seconds this command has
* @since 0.0.1
* @type {number}
* @readonly
*/
get cooldown() {
return this.cooldowns.cooldown / 1000;
}
/**
* The main category for the command
* @since 0.0.1
* @type {string}
* @readonly
*/
get category() {
return this.fullCategory[0] || 'General';
}
/**
* The sub category for the command
* @since 0.0.1
* @type {string}
* @readonly
*/
get subCategory() {
return this.fullCategory[1] || 'General';
}
/**
* The usage deliminator for the command input
* @since 0.0.1
* @type {?string}
* @readonly
*/
get usageDelim() {
return this.usage.usageDelim;
}
/**
* The usage string for the command
* @since 0.0.1
* @type {string}
* @readonly
*/
get usageString() {
return this.usage.usageString;
}
/**
* Creates a Usage to run custom prompts off of
* @param {string} usageString The string designating all parameters expected
* @param {string} usageDelim The string to delimit the input
* @returns {Usage}
*/
definePrompt(usageString, usageDelim) {
return new Usage(this.client, usageString, usageDelim);
}
/**
* Registers a one-off custom resolver. See tutorial {@link CommandsCustomResolvers}
* @since 0.5.0
* @param {string} type The type of the usage argument
* @param {Function} resolver The one-off custom resolver
* @returns {this}
* @chainable
*/
createCustomResolver(type, resolver) {
this.usage.createCustomResolver(type, resolver);
return this;
}
/**
* Customizes the response of an argument if it fails resolution. See tutorial {@link CommandsCustomResponses}
* @since 0.5.0
* @param {string} name The name of the usage argument
* @param {(string|Function)} response The custom response or i18n function
* @returns {this}
* @chainable
* @example
* // Changing the message for a parameter called 'targetUser'
* this.customizeResponse('targetUser', 'You did not give me a user...');
*
* // Or also using functions to have multilingual support:
* this.customizeResponse('targetUser', (message) =>
* message.language.get('COMMAND_REQUIRED_USER_FRIENDLY'));
*/
customizeResponse(name, response) {
this.usage.customizeResponse(name, response);
return this;
}
/**
* The run method to be overwritten in actual commands
* @since 0.0.1
* @param {KlasaMessage} message The command message mapped on top of the message used to trigger this command
* @param {any[]} params The fully resolved parameters based on your usage / usageDelim
* @returns {KlasaMessage|KlasaMessage[]} You should return the response message whenever possible
* @abstract
*/
async run() {
// Defined in extension Classes
throw new Error(`The run method has not been implemented by ${this.type}:${this.name}.`);
}
/**
* Defines the JSON.stringify behavior of this command.
* @returns {Object}
*/
toJSON() {
return {
...super.toJSON(),
requiredPermissions: this.requiredPermissions.toArray(false),
bucket: this.bucket,
category: this.category,
cooldown: this.cooldown,
deletable: this.deletable,
description: isFunction(this.description) ? this.description() : this.description,
extendedHelp: isFunction(this.extendedHelp) ? this.extendedHelp() : this.extendedHelp,
fullCategory: this.fullCategory,
guarded: this.guarded,
nsfw: this.nsfw,
permissionLevel: this.permissionLevel,
promptLimit: this.promptLimit,
promptTime: this.promptTime,
quotedStringSupport: this.quotedStringSupport,
requiredSettings: this.requiredSettings.slice(0),
runIn: this.runIn.slice(0),
subCategory: this.subCategory,
subcommands: this.subcommands,
usage: {
usageString: this.usage.usageString,
usageDelim: this.usage.usageDelim,
nearlyFullUsage: this.usage.nearlyFullUsage
},
usageDelim: this.usageDelim,
usageString: this.usageString
};
}
} |
JavaScript | class CacheTimestampsModel {
/**
*
* @param {string} cacheName
*
* @private
*/
constructor(cacheName) {
this._cacheName = cacheName;
this._db = new DBWrapper_js.DBWrapper(DB_NAME, 1, {
onupgradeneeded: event => this._handleUpgrade(event)
});
}
/**
* Should perform an upgrade of indexedDB.
*
* @param {Event} event
*
* @private
*/
_handleUpgrade(event) {
const db = event.target.result; // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
// have to use the `id` keyPath here and create our own values (a
// concatenation of `url + cacheName`) instead of simply using
// `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
const objStore = db.createObjectStore(OBJECT_STORE_NAME, {
keyPath: 'id'
}); // TODO(philipwalton): once we don't have to support EdgeHTML, we can
// create a single index with the keyPath `['cacheName', 'timestamp']`
// instead of doing both these indexes.
objStore.createIndex('cacheName', 'cacheName', {
unique: false
});
objStore.createIndex('timestamp', 'timestamp', {
unique: false
}); // Previous versions of `workbox-expiration` used `this._cacheName`
// as the IDBDatabase name.
deleteDatabase_js.deleteDatabase(this._cacheName);
}
/**
* @param {string} url
* @param {number} timestamp
*
* @private
*/
async setTimestamp(url, timestamp) {
url = normalizeURL(url);
const entry = {
url,
timestamp,
cacheName: this._cacheName,
// Creating an ID from the URL and cache name won't be necessary once
// Edge switches to Chromium and all browsers we support work with
// array keyPaths.
id: this._getId(url)
};
await this._db.put(OBJECT_STORE_NAME, entry);
}
/**
* Returns the timestamp stored for a given URL.
*
* @param {string} url
* @return {number}
*
* @private
*/
async getTimestamp(url) {
const entry = await this._db.get(OBJECT_STORE_NAME, this._getId(url));
return entry.timestamp;
}
/**
* Iterates through all the entries in the object store (from newest to
* oldest) and removes entries once either `maxCount` is reached or the
* entry's timestamp is less than `minTimestamp`.
*
* @param {number} minTimestamp
* @param {number} maxCount
* @return {Array<string>}
*
* @private
*/
async expireEntries(minTimestamp, maxCount) {
const entriesToDelete = await this._db.transaction(OBJECT_STORE_NAME, 'readwrite', (txn, done) => {
const store = txn.objectStore(OBJECT_STORE_NAME);
const request = store.index('timestamp').openCursor(null, 'prev');
const entriesToDelete = [];
let entriesNotDeletedCount = 0;
request.onsuccess = () => {
const cursor = request.result;
if (cursor) {
const result = cursor.value; // TODO(philipwalton): once we can use a multi-key index, we
// won't have to check `cacheName` here.
if (result.cacheName === this._cacheName) {
// Delete an entry if it's older than the max age or
// if we already have the max number allowed.
if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
// TODO(philipwalton): we should be able to delete the
// entry right here, but doing so causes an iteration
// bug in Safari stable (fixed in TP). Instead we can
// store the keys of the entries to delete, and then
// delete the separate transactions.
// https://github.com/GoogleChrome/workbox/issues/1978
// cursor.delete();
// We only need to return the URL, not the whole entry.
entriesToDelete.push(cursor.value);
} else {
entriesNotDeletedCount++;
}
}
cursor.continue();
} else {
done(entriesToDelete);
}
};
}); // TODO(philipwalton): once the Safari bug in the following issue is fixed,
// we should be able to remove this loop and do the entry deletion in the
// cursor loop above:
// https://github.com/GoogleChrome/workbox/issues/1978
const urlsDeleted = [];
for (const entry of entriesToDelete) {
await this._db.delete(OBJECT_STORE_NAME, entry.id);
urlsDeleted.push(entry.url);
}
return urlsDeleted;
}
/**
* Takes a URL and returns an ID that will be unique in the object store.
*
* @param {string} url
* @return {string}
*
* @private
*/
_getId(url) {
// Creating an ID from the URL and cache name won't be necessary once
// Edge switches to Chromium and all browsers we support work with
// array keyPaths.
return this._cacheName + '|' + normalizeURL(url);
}
} |
JavaScript | class CacheExpiration {
/**
* To construct a new CacheExpiration instance you must provide at least
* one of the `config` properties.
*
* @param {string} cacheName Name of the cache to apply restrictions to.
* @param {Object} config
* @param {number} [config.maxEntries] The maximum number of entries to cache.
* Entries used the least will be removed as the maximum is reached.
* @param {number} [config.maxAgeSeconds] The maximum age of an entry before
* it's treated as stale and removed.
*/
constructor(cacheName, config = {}) {
this._isRunning = false;
this._rerunRequested = false;
{
assert_js.assert.isType(cacheName, 'string', {
moduleName: 'workbox-expiration',
className: 'CacheExpiration',
funcName: 'constructor',
paramName: 'cacheName'
});
if (!(config.maxEntries || config.maxAgeSeconds)) {
throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
moduleName: 'workbox-expiration',
className: 'CacheExpiration',
funcName: 'constructor'
});
}
if (config.maxEntries) {
assert_js.assert.isType(config.maxEntries, 'number', {
moduleName: 'workbox-expiration',
className: 'CacheExpiration',
funcName: 'constructor',
paramName: 'config.maxEntries'
}); // TODO: Assert is positive
}
if (config.maxAgeSeconds) {
assert_js.assert.isType(config.maxAgeSeconds, 'number', {
moduleName: 'workbox-expiration',
className: 'CacheExpiration',
funcName: 'constructor',
paramName: 'config.maxAgeSeconds'
}); // TODO: Assert is positive
}
}
this._maxEntries = config.maxEntries;
this._maxAgeSeconds = config.maxAgeSeconds;
this._cacheName = cacheName;
this._timestampModel = new CacheTimestampsModel(cacheName);
}
/**
* Expires entries for the given cache and given criteria.
*/
async expireEntries() {
if (this._isRunning) {
this._rerunRequested = true;
return;
}
this._isRunning = true;
const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries); // Delete URLs from the cache
const cache = await self.caches.open(this._cacheName);
for (const url of urlsExpired) {
await cache.delete(url);
}
{
if (urlsExpired.length > 0) {
logger_js.logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` + `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` + `'${this._cacheName}' cache.`);
logger_js.logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
urlsExpired.forEach(url => logger_js.logger.log(` ${url}`));
logger_js.logger.groupEnd();
} else {
logger_js.logger.debug(`Cache expiration ran and found no entries to remove.`);
}
}
this._isRunning = false;
if (this._rerunRequested) {
this._rerunRequested = false;
dontWaitFor_js.dontWaitFor(this.expireEntries());
}
}
/**
* Update the timestamp for the given URL. This ensures the when
* removing entries based on maximum entries, most recently used
* is accurate or when expiring, the timestamp is up-to-date.
*
* @param {string} url
*/
async updateTimestamp(url) {
{
assert_js.assert.isType(url, 'string', {
moduleName: 'workbox-expiration',
className: 'CacheExpiration',
funcName: 'updateTimestamp',
paramName: 'url'
});
}
await this._timestampModel.setTimestamp(url, Date.now());
}
/**
* Can be used to check if a URL has expired or not before it's used.
*
* This requires a look up from IndexedDB, so can be slow.
*
* Note: This method will not remove the cached entry, call
* `expireEntries()` to remove indexedDB and Cache entries.
*
* @param {string} url
* @return {boolean}
*/
async isURLExpired(url) {
if (!this._maxAgeSeconds) {
{
throw new WorkboxError_js.WorkboxError(`expired-test-without-max-age`, {
methodName: 'isURLExpired',
paramName: 'maxAgeSeconds'
});
}
} else {
const timestamp = await this._timestampModel.getTimestamp(url);
const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
return timestamp < expireOlderThan;
}
}
/**
* Removes the IndexedDB object store used to keep track of cache expiration
* metadata.
*/
async delete() {
// Make sure we don't attempt another rerun if we're called in the middle of
// a cache expiration.
this._rerunRequested = false;
await this._timestampModel.expireEntries(Infinity); // Expires all.
}
} |
JavaScript | class ExpirationPlugin {
/**
* @param {Object} config
* @param {number} [config.maxEntries] The maximum number of entries to cache.
* Entries used the least will be removed as the maximum is reached.
* @param {number} [config.maxAgeSeconds] The maximum age of an entry before
* it's treated as stale and removed.
* @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
* automatic deletion if the available storage quota has been exceeded.
*/
constructor(config = {}) {
/**
* A "lifecycle" callback that will be triggered automatically by the
* `workbox-strategies` handlers when a `Response` is about to be returned
* from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
* the handler. It allows the `Response` to be inspected for freshness and
* prevents it from being used if the `Response`'s `Date` header value is
* older than the configured `maxAgeSeconds`.
*
* @param {Object} options
* @param {string} options.cacheName Name of the cache the response is in.
* @param {Response} options.cachedResponse The `Response` object that's been
* read from a cache and whose freshness should be checked.
* @return {Response} Either the `cachedResponse`, if it's
* fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
*
* @private
*/
this.cachedResponseWillBeUsed = async ({
event,
request,
cacheName,
cachedResponse
}) => {
if (!cachedResponse) {
return null;
}
const isFresh = this._isResponseDateFresh(cachedResponse); // Expire entries to ensure that even if the expiration date has
// expired, it'll only be used once.
const cacheExpiration = this._getCacheExpiration(cacheName);
dontWaitFor_js.dontWaitFor(cacheExpiration.expireEntries()); // Update the metadata for the request URL to the current timestamp,
// but don't `await` it as we don't want to block the response.
const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
if (event) {
try {
event.waitUntil(updateTimestampDone);
} catch (error) {
{
// The event may not be a fetch event; only log the URL if it is.
if ('request' in event) {
logger_js.logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL_js.getFriendlyURL(event.request.url)}'.`);
}
}
}
}
return isFresh ? cachedResponse : null;
};
/**
* A "lifecycle" callback that will be triggered automatically by the
* `workbox-strategies` handlers when an entry is added to a cache.
*
* @param {Object} options
* @param {string} options.cacheName Name of the cache that was updated.
* @param {string} options.request The Request for the cached entry.
*
* @private
*/
this.cacheDidUpdate = async ({
cacheName,
request
}) => {
{
assert_js.assert.isType(cacheName, 'string', {
moduleName: 'workbox-expiration',
className: 'Plugin',
funcName: 'cacheDidUpdate',
paramName: 'cacheName'
});
assert_js.assert.isInstance(request, Request, {
moduleName: 'workbox-expiration',
className: 'Plugin',
funcName: 'cacheDidUpdate',
paramName: 'request'
});
}
const cacheExpiration = this._getCacheExpiration(cacheName);
await cacheExpiration.updateTimestamp(request.url);
await cacheExpiration.expireEntries();
};
{
if (!(config.maxEntries || config.maxAgeSeconds)) {
throw new WorkboxError_js.WorkboxError('max-entries-or-age-required', {
moduleName: 'workbox-expiration',
className: 'Plugin',
funcName: 'constructor'
});
}
if (config.maxEntries) {
assert_js.assert.isType(config.maxEntries, 'number', {
moduleName: 'workbox-expiration',
className: 'Plugin',
funcName: 'constructor',
paramName: 'config.maxEntries'
});
}
if (config.maxAgeSeconds) {
assert_js.assert.isType(config.maxAgeSeconds, 'number', {
moduleName: 'workbox-expiration',
className: 'Plugin',
funcName: 'constructor',
paramName: 'config.maxAgeSeconds'
});
}
}
this._config = config;
this._maxAgeSeconds = config.maxAgeSeconds;
this._cacheExpirations = new Map();
if (config.purgeOnQuotaError) {
registerQuotaErrorCallback_js.registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
}
}
/**
* A simple helper method to return a CacheExpiration instance for a given
* cache name.
*
* @param {string} cacheName
* @return {CacheExpiration}
*
* @private
*/
_getCacheExpiration(cacheName) {
if (cacheName === cacheNames_js.cacheNames.getRuntimeName()) {
throw new WorkboxError_js.WorkboxError('expire-custom-caches-only');
}
let cacheExpiration = this._cacheExpirations.get(cacheName);
if (!cacheExpiration) {
cacheExpiration = new CacheExpiration(cacheName, this._config);
this._cacheExpirations.set(cacheName, cacheExpiration);
}
return cacheExpiration;
}
/**
* @param {Response} cachedResponse
* @return {boolean}
*
* @private
*/
_isResponseDateFresh(cachedResponse) {
if (!this._maxAgeSeconds) {
// We aren't expiring by age, so return true, it's fresh
return true;
} // Check if the 'date' header will suffice a quick expiration check.
// See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
// discussion.
const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
if (dateHeaderTimestamp === null) {
// Unable to parse date, so assume it's fresh.
return true;
} // If we have a valid headerTime, then our response is fresh iff the
// headerTime plus maxAgeSeconds is greater than the current time.
const now = Date.now();
return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
}
/**
* This method will extract the data header and parse it into a useful
* value.
*
* @param {Response} cachedResponse
* @return {number|null}
*
* @private
*/
_getDateHeaderTimestamp(cachedResponse) {
if (!cachedResponse.headers.has('date')) {
return null;
}
const dateHeader = cachedResponse.headers.get('date');
const parsedDate = new Date(dateHeader);
const headerTime = parsedDate.getTime(); // If the Date header was invalid for some reason, parsedDate.getTime()
// will return NaN.
if (isNaN(headerTime)) {
return null;
}
return headerTime;
}
/**
* This is a helper method that performs two operations:
*
* - Deletes *all* the underlying Cache instances associated with this plugin
* instance, by calling caches.delete() on your behalf.
* - Deletes the metadata from IndexedDB used to keep track of expiration
* details for each Cache instance.
*
* When using cache expiration, calling this method is preferable to calling
* `caches.delete()` directly, since this will ensure that the IndexedDB
* metadata is also cleanly removed and open IndexedDB instances are deleted.
*
* Note that if you're *not* using cache expiration for a given cache, calling
* `caches.delete()` and passing in the cache's name should be sufficient.
* There is no Workbox-specific method needed for cleanup in that case.
*/
async deleteCacheAndMetadata() {
// Do this one at a time instead of all at once via `Promise.all()` to
// reduce the chance of inconsistency if a promise rejects.
for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
await self.caches.delete(cacheName);
await cacheExpiration.delete();
} // Reset this._cacheExpirations to its initial state.
this._cacheExpirations = new Map();
}
} |
JavaScript | class Planos_de_Acao extends Component {
constructor(props) {
super(props);
this.state = {
termoAceito1: false,
termoAceito2: false,
termoAceito3: false,
termoAceito4: false,
};
}
checkTermoAceito1 = () => {
if(this.state.termoAceito1 === false){
this.setState({ termoAceito1: true })
} else{
this.setState({ termoAceito1: false })
}
};
checkTermoAceito2 = () => {
if(this.state.termoAceito2 === false){
this.setState({ termoAceito2: true })
} else{
this.setState({ termoAceito2: false })
}
};
checkTermoAceito3 = () => {
if(this.state.termoAceito3 === false){
this.setState({ termoAceito3: true })
} else{
this.setState({ termoAceito3: false })
}
};
checkTermoAceito4 = () => {
if(this.state.termoAceito4 === false){
this.setState({ termoAceito4: true })
} else{
this.setState({ termoAceito4: false })
}
};
render() {
return (
<Container>
<MenuButton navigation={this.props.navigation} />
<Header style={styles.headerStyle}>
<Text style={styles.textTitle}>Planos De Ação</Text>
</Header>
<Content>
<ListItem selected={false} >
<Left>
<Text style={styles.buttonText}>Plano de Incêndio</Text>
</Left>
<Right>
<Radio
color={"#000000"}
selectedColor={"#ff0000"}
selected={this.state.termoAceito1}
onPress={this.checkTermoAceito1}
/>
</Right>
</ListItem>
<ListItem selected={true}>
<Left>
<Text style={styles.buttonText}>Plano de Enchente</Text>
</Left>
<Right>
<Radio
color={"#000000"}
selectedColor={"#ff0000"}
selected={this.state.termoAceito2}
onPress={this.checkTermoAceito2}
/>
</Right>
</ListItem>
<ListItem selected={false} >
<Left>
<Text style={styles.buttonText}>Plano para Terremoto</Text>
</Left>
<Right>
<Radio
color={"#000000"}
selectedColor={"#ff0000"}
selected={this.state.termoAceito3}
onPress={this.checkTermoAceito3}
/>
</Right>
</ListItem>
<ListItem selected={false} >
<Left>
<Text style={styles.buttonText}>Plano X</Text>
</Left>
<Right>
<Radio
color={"#000000"}
selectedColor={"#ff0000"}
selected={this.state.termoAceito4}
onPress={this.checkTermoAceito4}
/>
</Right>
</ListItem>
</Content>
<TouchableOpacity
style={styles.buttonContainer}
onPress={this.handleSubmit}
>
<Text style={styles.buttonText}>Executar Plano!</Text>
</TouchableOpacity>
</Container>
);
}
} |
JavaScript | class Delivery {
/**
* Create a Delivery Calculator.
* @param {Number} costPerDelivery
* @param {Number} costPerProduct
* @param {Number} fixedCost
*/
constructor (costPerDelivery = 0, costPerProduct = 0, fixedCost = 2.99) {
this.costPerDelivery = costPerDelivery
this.costPerProduct = costPerProduct
this.fixedCost = fixedCost
}
/**
* Delivery calculator calculates dynamically delivery costs by cart properties.
* @param {Cart} cart
* @returns {Number}
*/
calculateFor (cart) {
if (!cart) {
throw new Error('Delivery cost calculator needs to apply a cart.')
}
return (
(this.costPerDelivery * cart.distinctCategoryCount) +
(this.costPerProduct * cart.products.length) +
this.fixedCost
)
}
} |
JavaScript | class EthfinexClient extends BasicClient {
constructor() {
super("wss://api.ethfinex.com/ws/", "Ethfinex");
this._channels = {};
this.hasTickers = true;
this.hasTrades = true;
this.hasLevel2Updates = true;
this.hasLevel3Updates = true;
}
_sendSubTicker(remote_id) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "ticker",
pair: remote_id,
})
);
}
_sendUnsubTicker(remote_id) {
this._wss.send(
JSON.stringify({
event: "unsubscribe",
channel: "ticker",
pair: remote_id,
})
);
}
_sendSubTrades(remote_id) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "trades",
pair: remote_id,
})
);
}
_sendUnsubTrades(remote_id) {
let chanId = this._findChannel("trades", remote_id);
this._sendUnsubscribe(chanId);
}
_sendSubLevel2Updates(remote_id) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "book",
pair: remote_id,
length: "100",
})
);
}
_sendUnsubLevel2Updates(remote_id) {
let chanId = this._findChannel("level2updates", remote_id);
this._sendUnsubscribe(chanId);
}
_sendSubLevel3Updates(remote_id) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "book",
pair: remote_id,
prec: "R0",
length: "100",
})
);
}
_sendUnsubLevel3Updates(remote_id) {
let chanId = this._findChannel("level3updates", remote_id);
this._sendUnsubscribe(chanId);
}
_sendUnsubscribe(chanId) {
if (chanId) {
this._wss.send(
JSON.stringify({
event: "unsubscribe",
chanId: chanId,
})
);
}
}
_findChannel(type, remote_id) {
for (let chan of Object.values(this._channels)) {
if (chan.pair === remote_id) {
if (type === "trades" && chan.channel === "trades") return chan.chanId;
if (type === "level2updates" && chan.channel === "book" && chan.prec !== "R0")
return chan.chanId;
if (type === "level3updates" && chan.channel === "book" && chan.prec === "R0")
return chan.chanId;
}
}
}
_onMessage(raw) {
let msg = JSON.parse(raw);
// capture channel metadata
if (msg.event === "subscribed") {
this._channels[msg.chanId] = msg;
return;
}
// lookup channel
let channel = this._channels[msg[0]];
if (!channel) return;
// ignore heartbeats
if (msg[1] === "hb") return;
if (channel.channel === "ticker") {
this._onTicker(msg, channel);
return;
}
// trades
if (channel.channel === "trades" && msg[1] === "tu") {
this._onTradeMessage(msg, channel);
return;
}
// level3
if (channel.channel === "book" && channel.prec === "R0") {
if (Array.isArray(msg[1])) this._onLevel3Snapshot(msg, channel);
else this._onLevel3Update(msg, channel);
return;
}
// level2
if (channel.channel === "book") {
if (Array.isArray(msg[1])) this._onLevel2Snapshot(msg, channel);
else this._onLevel2Update(msg, channel);
return;
}
}
_onTicker(msg) {
let [chanId, bid, bidSize, ask, askSize, change, changePercent, last, volume, high, low] = msg;
let remote_id = this._channels[chanId].pair;
let market = this._tickerSubs.get(remote_id);
if (!market) return;
let open = last + change;
let ticker = new Ticker({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
timestamp: Date.now(),
last: last.toFixed(12),
open: open.toFixed(12),
high: high.toFixed(12),
low: low.toFixed(12),
volume: volume.toFixed(12),
change: change.toFixed(12),
changePercent: changePercent.toFixed(2),
bid: bid.toFixed(12),
bidVolume: bidSize.toFixed(12),
ask: ask.toFixed(12),
askVolume: askSize.toFixed(12),
});
this.emit("ticker", ticker, market);
}
_onTradeMessage(msg) {
let [chanId, , , id, unix, price, amount] = msg;
let remote_id = this._channels[chanId].pair;
let market = this._tradeSubs.get(remote_id);
if (!market) return;
let side = amount > 0 ? "buy" : "sell";
price = price.toFixed(12);
amount = Math.abs(amount).toFixed(12);
let trade = new Trade({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
tradeId: id.toFixed(),
unix: unix * 1000,
side,
price,
amount,
});
this.emit("trade", trade, market);
}
_onLevel2Snapshot(msg) {
let remote_id = this._channels[msg[0]].pair;
let market = this._level2UpdateSubs.get(remote_id); // this message will be coming from an l2update
if (!market) return;
let bids = [];
let asks = [];
for (let [price, count, size] of msg[1]) {
let isBid = size > 0;
let result = new Level2Point(price.toFixed(12), Math.abs(size).toFixed(12), count.toFixed(0));
if (isBid) bids.push(result);
else asks.push(result);
}
let result = new Level2Snapshot({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
bids,
asks,
});
this.emit("l2snapshot", result, market);
}
_onLevel2Update(msg) {
let [channel, price, count, size] = msg;
let remote_id = this._channels[channel].pair;
let market = this._level2UpdateSubs.get(remote_id);
if (!market) return;
let point = new Level2Point(price.toFixed(12), Math.abs(size).toFixed(12), count.toFixed(0));
let asks = [];
let bids = [];
let isBid = size > 0;
if (isBid) bids.push(point);
else asks.push(point);
let isDelete = count === 0;
if (isDelete) point.size = (0).toFixed(12); // reset the size to 0, comes in as 1 or -1 to indicate bid/ask
let update = new Level2Update({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
asks,
bids,
});
this.emit("l2update", update, market);
}
_onLevel3Snapshot(msg, channel) {
let remote_id = channel.pair;
let market = this._level3UpdateSubs.get(remote_id); // this message will be coming from an l2update
if (!market) return;
let bids = [];
let asks = [];
msg[1].forEach(p => {
let point = new Level3Point(p[0].toFixed(), p[1].toFixed(12), Math.abs(p[2]).toFixed(12));
if (p[2] > 0) bids.push(point);
else asks.push(point);
});
let result = new Level3Snapshot({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
asks,
bids,
});
this.emit("l3snapshot", result, market);
}
_onLevel3Update(msg, channel) {
let remote_id = channel.pair;
let market = this._level3UpdateSubs.get(remote_id);
if (!market) return;
let bids = [];
let asks = [];
let point = new Level3Point(msg[1].toFixed(), msg[2].toFixed(12), Math.abs(msg[3]).toFixed(12));
if (msg[3] > 0) bids.push(point);
else asks.push(point);
let result = new Level3Update({
exchange: "Ethfinex",
base: market.base,
quote: market.quote,
asks,
bids,
});
this.emit("l3update", result, market);
}
} |
JavaScript | class AmpFetcher {
/**
* @param {!Window} win
*/
constructor(win) {
/** @const @private {!../../../src/service/xhr-impl.Xhr} */
this.xhr_ = Services.xhrFor(win);
/** @private @const {!Window} */
this.win_ = win;
}
/** @override */
fetchCredentialedJson(url) {
return this.xhr_
.fetchJson(url, {
credentials: 'include',
prerenderSafe: true,
})
.then((response) => response.json());
}
/** @override */
fetch(input, opt_init) {
return this.xhr_.fetch(input, opt_init); //needed to kepp closure happy
}
/** @override */
sendPost(url, message) {
const init = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
credentials: 'include',
body:
'f.req=' +
JSON.stringify(/** @type {JsonObject} */ (message.toArray(false))),
};
return this.fetch(url, init).then(
(response) => (response && response.json()) || {}
);
}
/**
* POST data to a URL endpoint, do not wait for a response.
* @param {string} url
* @param {string|!Object} data
*/
sendBeacon(url, data) {
const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
const body =
'f.req=' +
JSON.stringify(/** @type {JsonObject} */ (data.toArray(false)));
const sendBeacon = WindowInterface.getSendBeacon(this.win_);
if (sendBeacon) {
const blob = new Blob([body], {type: contentType});
sendBeacon(url, blob);
return;
}
// Only newer browsers support beacon. Fallback to standard XHR POST.
const init = {
method: 'POST',
headers: {'Content-Type': contentType},
credentials: 'include',
body,
};
this.fetch(url, init);
}
} |
JavaScript | class VolumeManagerImpl extends EventTarget {
constructor() {
super();
/** @override */
this.volumeInfoList = new VolumeInfoListImpl();
/**
* The list of archives requested to mount. We will show contents once
* archive is mounted, but only for mounts from within this filebrowser tab.
* @type {Object<Object>}
* @private
*/
this.requests_ = {};
// The status should be merged into VolumeManager.
// TODO(hidehiko): Remove them after the migration.
/**
* Connection state of the Drive.
* @type {chrome.fileManagerPrivate.DriveConnectionState}
* @private
*/
this.driveConnectionState_ = {
type: chrome.fileManagerPrivate.DriveConnectionStateType.OFFLINE,
reason: chrome.fileManagerPrivate.DriveOfflineReason.NO_SERVICE,
hasCellularNetworkAccess: false,
canPinHostedFiles: false,
};
chrome.fileManagerPrivate.onDriveConnectionStatusChanged.addListener(
this.onDriveConnectionStatusChanged_.bind(this));
this.onDriveConnectionStatusChanged_();
/**
* Holds the resolver for the `waitForInitialization_` promise.
* @private {null|function():void}
*/
this.finishInitialization_ = null;
/**
* Promise used to wait for the initialize() method to finish.
* @private {!Promise<void>}
*/
this.waitForInitialization_ =
new Promise(resolve => this.finishInitialization_ = resolve);
// Subscribe to mount event as early as possible, but after the
// waitForInitialization_ above.
chrome.fileManagerPrivate.onMountCompleted.addListener(
this.onMountCompleted_.bind(this));
}
/** @override */
dispose() {}
/**
* Invoked when the drive connection status is changed.
* @private
*/
onDriveConnectionStatusChanged_() {
chrome.fileManagerPrivate.getDriveConnectionState(state => {
this.driveConnectionState_ = state;
dispatchSimpleEvent(this, 'drive-connection-changed');
});
}
/** @override */
getDriveConnectionState() {
return this.driveConnectionState_;
}
/**
* Adds new volume info from the given volumeMetadata. If the corresponding
* volume info has already been added, the volumeMetadata is ignored.
* @param {!VolumeInfo} volumeInfo
* @return {!Promise<!VolumeInfo>}
* @private
*/
async addVolumeInfo_(volumeInfo) {
const volumeType = volumeInfo.volumeType;
// We don't show Downloads and Drive on volume list if they have
// mount error, since users can do nothing in this situation. We
// show Removable and Provided volumes regardless of mount error
// so that users can unmount or format the volume.
// TODO(fukino): Once the Files app gets ready, show erroneous
// Drive volume so that users can see auth warning banner on the
// volume. crbug.com/517772.
let shouldShow = true;
switch (volumeType) {
case VolumeManagerCommon.VolumeType.DOWNLOADS:
case VolumeManagerCommon.VolumeType.DRIVE:
shouldShow = !!volumeInfo.fileSystem;
break;
}
if (!shouldShow) {
return volumeInfo;
}
if (this.volumeInfoList.findIndex(volumeInfo.volumeId) === -1) {
this.volumeInfoList.add(volumeInfo);
// Update the network connection status, because until the drive
// is initialized, the status is set to not ready.
// TODO(mtomasz): The connection status should be migrated into
// chrome.fileManagerPrivate.VolumeMetadata.
if (volumeType === VolumeManagerCommon.VolumeType.DRIVE) {
this.onDriveConnectionStatusChanged_();
}
} else if (volumeType === VolumeManagerCommon.VolumeType.REMOVABLE) {
// Update for remounted USB external storage, because they were
// remounted to switch read-only policy.
this.volumeInfoList.add(volumeInfo);
}
return volumeInfo;
}
/**
* Initializes mount points.
* @return {!Promise<void>}
*/
async initialize() {
let finished = false;
/**
* Resolves the initialization promise to unblock any code awaiting for
* it.
*/
const finishInitialization = () => {
if (finished) {
return;
}
finished = true;
this.finishInitialization_();
};
try {
console.warn('Getting volumes');
let volumeMetadataList = await new Promise(
resolve => chrome.fileManagerPrivate.getVolumeMetadataList(resolve));
if (!volumeMetadataList) {
console.error('Cannot get volumes');
finishInitialization();
return;
}
volumeMetadataList = volumeMetadataList.filter(volume => !volume.hidden);
console.debug(`There are ${volumeMetadataList.length} volumes`);
let counter = 0;
// Create VolumeInfo for each volume.
volumeMetadataList.map(async (volumeMetadata, idx) => {
const volumeId = volumeMetadata.volumeId;
let volumeInfo = null;
try {
console.debug(`Initializing volume #${idx} '${volumeId}'`);
// createVolumeInfo() requests the filesystem and resolve its root,
// after that it only creates a VolumeInfo.
volumeInfo = await volumeManagerUtil.createVolumeInfo(volumeMetadata);
// Add addVolumeInfo_() changes the VolumeInfoList which propagates
// to the foreground.
await this.addVolumeInfo_(volumeInfo);
console.debug(`Initialized volume #${idx} ${volumeId}'`);
} catch (error) {
console.warn(`Error initiliazing #${idx} ${volumeId}`);
console.error(error);
} finally {
counter += 1;
// Finish after all volumes have been processed, or at least Downloads
// or Drive.
const isDriveOrDownloads = volumeInfo &&
(volumeInfo.volumeType ==
VolumeManagerCommon.VolumeType.DOWNLOADS ||
volumeInfo.volumeType == VolumeManagerCommon.VolumeType.DRIVE);
if (counter === volumeMetadataList.length || isDriveOrDownloads) {
finishInitialization();
}
}
});
// At this point the volumes are still initializing.
console.warn(
`Queued the initialization of all ` +
`${volumeMetadataList.length} volumes`);
if (volumeMetadataList.length === 0) {
finishInitialization();
}
} catch (error) {
finishInitialization();
throw error;
}
}
/**
* Event handler called when some volume was mounted or unmounted.
* @param {chrome.fileManagerPrivate.MountCompletedEvent} event
* @private
*/
async onMountCompleted_(event) {
// Wait for the initialization to guarantee that the initialize() runs for
// some volumes before any mount event, because the mounted volume can be
// unresponsive, getting stuck when resolving the root in the method
// createVolumeInfo(). crbug.com/504366
await this.waitForInitialization_;
const {eventType, status, volumeMetadata} = event;
const {sourcePath = '', volumeId} = volumeMetadata;
switch (eventType) {
case 'mount': {
const requestKey = this.makeRequestKey_('mount', sourcePath);
switch (status) {
case 'success':
case VolumeManagerCommon.VolumeError.UNKNOWN_FILESYSTEM:
case VolumeManagerCommon.VolumeError.UNSUPPORTED_FILESYSTEM: {
if (volumeMetadata.hidden) {
console.debug(`Mount discarded for hidden volume: '${volumeId}'`);
this.finishRequest_(requestKey, status);
return;
}
console.debug(`Mounted '${sourcePath}' as '${volumeId}'`);
const volumeInfo =
await volumeManagerUtil.createVolumeInfo(volumeMetadata);
await this.addVolumeInfo_(volumeInfo);
this.finishRequest_(requestKey, status, volumeInfo);
return;
}
case VolumeManagerCommon.VolumeError.ALREADY_MOUNTED: {
console.warn(`'Cannot mount ${sourcePath}': Already mounted as '${
volumeId}'`);
const navigationEvent =
new Event(VolumeManagerCommon.VOLUME_ALREADY_MOUNTED);
navigationEvent.volumeId = volumeId;
this.dispatchEvent(navigationEvent);
this.finishRequest_(requestKey, status);
return;
}
case VolumeManagerCommon.VolumeError.NEED_PASSWORD: {
console.warn(`'Cannot mount ${sourcePath}': ${status}`);
this.finishRequest_(requestKey, status);
return;
}
default:
console.error(`Cannot mount '${sourcePath}': ${status}`);
this.finishRequest_(requestKey, status);
return;
}
}
case 'unmount': {
const requestKey = this.makeRequestKey_('unmount', volumeId);
const volumeInfoIndex = this.volumeInfoList.findIndex(volumeId);
const volumeInfo = volumeInfoIndex !== -1 ?
this.volumeInfoList.item(volumeInfoIndex) :
null;
switch (status) {
case 'success': {
const requested = requestKey in this.requests_;
if (!requested && volumeInfo) {
console.warn(`Unmounted '${volumeId}' without request`);
this.dispatchEvent(new CustomEvent(
'externally-unmounted', {detail: volumeInfo}));
} else {
console.debug(`Unmounted '${volumeId}'`);
}
this.volumeInfoList.remove(volumeId);
this.finishRequest_(requestKey, status);
return;
}
default:
console.error(`Cannot unmount '${volumeId}': ${status}`);
this.finishRequest_(requestKey, status);
return;
}
}
}
}
/**
* Creates string to match mount events with requests.
* @param {string} requestType 'mount' | 'unmount'. TODO(hidehiko): Replace by
* enum.
* @param {string} argument Argument describing the request, eg. source file
* path of the archive to be mounted, or a volumeId for unmounting.
* @return {string} Key for |this.requests_|.
* @private
*/
makeRequestKey_(requestType, argument) {
return requestType + ':' + argument;
}
/** @override */
async mountArchive(fileUrl, password) {
const path = await new Promise(resolve => {
chrome.fileManagerPrivate.addMount(fileUrl, password, resolve);
});
console.debug(`Mounting '${path}'`);
const key = this.makeRequestKey_('mount', path);
return this.startRequest_(key);
}
/** @override */
async unmount({volumeId}) {
console.warn(`Unmounting '${volumeId}'`);
chrome.fileManagerPrivate.removeMount(volumeId);
const key = this.makeRequestKey_('unmount', volumeId);
await this.startRequest_(key);
}
/** @override */
configure(volumeInfo) {
return new Promise((fulfill, reject) => {
chrome.fileManagerPrivate.configureVolume(volumeInfo.volumeId, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError.message);
} else {
fulfill();
}
});
});
}
/** @override */
getVolumeInfo(entry) {
if (!entry) {
console.error(`Invalid entry passed to getVolumeInfo: ${entry}`);
return null;
}
for (let i = 0; i < this.volumeInfoList.length; i++) {
const volumeInfo = this.volumeInfoList.item(i);
if (volumeInfo.fileSystem &&
util.isSameFileSystem(volumeInfo.fileSystem, entry.filesystem)) {
return volumeInfo;
}
// Additionally, check fake entries.
for (const key in volumeInfo.fakeEntries) {
const fakeEntry = volumeInfo.fakeEntries[key];
if (util.isSameEntry(fakeEntry, entry)) {
return volumeInfo;
}
}
}
return null;
}
/** @override */
getCurrentProfileVolumeInfo(volumeType) {
for (let i = 0; i < this.volumeInfoList.length; i++) {
const volumeInfo = this.volumeInfoList.item(i);
if (volumeInfo.profile.isCurrentProfile &&
volumeInfo.volumeType === volumeType) {
return volumeInfo;
}
}
return null;
}
/** @override */
getLocationInfo(entry) {
if (!entry) {
console.error(`Invalid entry passed to getLocationInfo: ${entry}`);
return null;
}
const volumeInfo = this.getVolumeInfo(entry);
if (util.isFakeEntry(entry)) {
return new EntryLocationImpl(
volumeInfo, assert(entry.rootType),
true /* the entry points a root directory. */,
true /* fake entries are read only. */);
}
if (!volumeInfo) {
return null;
}
let rootType;
let isReadOnly;
let isRootEntry;
if (volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DRIVE) {
// For Drive, the roots are /root, /team_drives, /Computers and /other,
// instead of /. Root URLs contain trailing slashes.
if (entry.fullPath == '/root' || entry.fullPath.indexOf('/root/') === 0) {
rootType = VolumeManagerCommon.RootType.DRIVE;
isReadOnly = volumeInfo.isReadOnly;
isRootEntry = entry.fullPath === '/root';
} else if (
entry.fullPath == VolumeManagerCommon.SHARED_DRIVES_DIRECTORY_PATH ||
entry.fullPath.indexOf(
VolumeManagerCommon.SHARED_DRIVES_DIRECTORY_PATH + '/') === 0) {
if (entry.fullPath ==
VolumeManagerCommon.SHARED_DRIVES_DIRECTORY_PATH) {
rootType = VolumeManagerCommon.RootType.SHARED_DRIVES_GRAND_ROOT;
isReadOnly = true;
isRootEntry = true;
} else {
rootType = VolumeManagerCommon.RootType.SHARED_DRIVE;
if (util.isTeamDriveRoot(entry)) {
isReadOnly = false;
isRootEntry = true;
} else {
// Regular files/directories under Shared Drives.
isRootEntry = false;
isReadOnly = volumeInfo.isReadOnly;
}
}
} else if (
entry.fullPath == VolumeManagerCommon.COMPUTERS_DIRECTORY_PATH ||
entry.fullPath.indexOf(
VolumeManagerCommon.COMPUTERS_DIRECTORY_PATH + '/') === 0) {
if (entry.fullPath == VolumeManagerCommon.COMPUTERS_DIRECTORY_PATH) {
rootType = VolumeManagerCommon.RootType.COMPUTERS_GRAND_ROOT;
isReadOnly = true;
isRootEntry = true;
} else {
rootType = VolumeManagerCommon.RootType.COMPUTER;
if (util.isComputersRoot(entry)) {
isReadOnly = true;
isRootEntry = true;
} else {
// Regular files/directories under a Computer entry.
isRootEntry = false;
isReadOnly = volumeInfo.isReadOnly;
}
}
} else if (
entry.fullPath === '/.files-by-id' ||
entry.fullPath.indexOf('/.files-by-id/') === 0) {
rootType = VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME;
// /.files-by-id/<id> is read-only, but /.files-by-id/<id>/foo is
// read-write.
isReadOnly = entry.fullPath.split('/').length < 4;
isRootEntry = entry.fullPath === '/.files-by-id';
} else if (
entry.fullPath === '/.shortcut-targets-by-id' ||
entry.fullPath.indexOf('/.shortcut-targets-by-id/') === 0) {
rootType = VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME;
// /.shortcut-targets-by-id/<id> is read-only, but
// /.shortcut-targets-by-id/<id>/foo is read-write.
isReadOnly = entry.fullPath.split('/').length < 4;
isRootEntry = entry.fullPath === '/.shortcut-targets-by-id';
} else if (
entry.fullPath === '/.Trash-1000' ||
entry.fullPath.indexOf('/.Trash-1000/') === 0) {
// Drive uses "$topdir/.Trash-$uid" as the trash dir as per XDG spec.
// User chronos is always uid 1000.
rootType = VolumeManagerCommon.RootType.TRASH;
isReadOnly = false;
isRootEntry = entry.fullPath === '/.Trash-1000';
} else {
// Accessing Drive files outside of /drive/root and /drive/other is not
// allowed, but can happen. Therefore returning null.
return null;
}
} else {
rootType = VolumeManagerCommon.getRootTypeFromVolumeType(
assert(volumeInfo.volumeType));
isRootEntry = util.isSameEntry(entry, volumeInfo.fileSystem.root);
// Although "Play files" root directory is writable in file system level,
// we prohibit write operations on it in the UI level to avoid confusion.
// Users can still have write access in sub directories like
// /Play files/Pictures, /Play files/DCIM, etc...
if (volumeInfo.volumeType ==
VolumeManagerCommon.VolumeType.ANDROID_FILES &&
isRootEntry) {
isReadOnly = true;
} else {
isReadOnly = volumeInfo.isReadOnly;
}
}
return new EntryLocationImpl(volumeInfo, rootType, isRootEntry, isReadOnly);
}
/** @override */
findByDevicePath(devicePath) {
for (let i = 0; i < this.volumeInfoList.length; i++) {
const volumeInfo = this.volumeInfoList.item(i);
if (volumeInfo.devicePath && volumeInfo.devicePath === devicePath) {
return volumeInfo;
}
}
return null;
}
/** @override */
whenVolumeInfoReady(volumeId) {
return new Promise((fulfill) => {
const handler = () => {
const index = this.volumeInfoList.findIndex(volumeId);
if (index !== -1) {
fulfill(this.volumeInfoList.item(index));
this.volumeInfoList.removeEventListener('splice', handler);
}
};
this.volumeInfoList.addEventListener('splice', handler);
handler();
});
}
/** @override */
getDefaultDisplayRoot(callback) {
console.error('Unexpected call to VolumeManagerImpl.getDefaultDisplayRoot');
callback(null);
}
/**
* @param {string} key Key produced by |makeRequestKey_|.
* @return {!Promise<!VolumeInfo>} Fulfilled on success, otherwise rejected
* with a VolumeManagerCommon.VolumeError.
* @private
*/
startRequest_(key) {
return new Promise((successCallback, errorCallback) => {
if (key in this.requests_) {
const request = this.requests_[key];
request.successCallbacks.push(successCallback);
request.errorCallbacks.push(errorCallback);
} else {
this.requests_[key] = {
successCallbacks: [successCallback],
errorCallbacks: [errorCallback],
timeout: setTimeout(
this.onTimeout_.bind(this, key), volumeManagerUtil.TIMEOUT)
};
}
});
}
/**
* Called if no response received in |TIMEOUT|.
* @param {string} key Key produced by |makeRequestKey_|.
* @private
*/
onTimeout_(key) {
this.invokeRequestCallbacks_(
this.requests_[key], VolumeManagerCommon.VolumeError.TIMEOUT);
delete this.requests_[key];
}
/**
* @param {string} key Key produced by |makeRequestKey_|.
* @param {!VolumeManagerCommon.VolumeError|string} status Status received
* from the API.
* @param {VolumeInfo=} opt_volumeInfo Volume info of the mounted volume.
* @private
*/
finishRequest_(key, status, opt_volumeInfo) {
const request = this.requests_[key];
if (!request) {
return;
}
clearTimeout(request.timeout);
this.invokeRequestCallbacks_(request, status, opt_volumeInfo);
delete this.requests_[key];
}
/**
* @param {Object} request Structure created in |startRequest_|.
* @param {!VolumeManagerCommon.VolumeError|string} status If status ===
* 'success' success callbacks are called.
* @param {VolumeInfo=} opt_volumeInfo Volume info of the mounted volume.
* @private
*/
invokeRequestCallbacks_(request, status, opt_volumeInfo) {
const callEach = (callbacks, self, args) => {
for (let i = 0; i < callbacks.length; i++) {
callbacks[i].apply(self, args);
}
};
if (status === 'success') {
callEach(request.successCallbacks, this, [opt_volumeInfo]);
} else {
volumeManagerUtil.validateError(status);
callEach(request.errorCallbacks, this, [status]);
}
}
} |
JavaScript | class ThriftServer extends EventEmitter {
/**
* config options
* @param {Object} options config include:
* {
* 1. adapter: { // {Object} config
* [name='zookeeper'] // redis or zookeeper
* [options={}] // options of adapter
* }
* 2. [services] // {Array|Object} handler config, a array list or only one,
* or you can use `.add` to add new one (for js)
* 3. thrift: { // thrift config
* [port]: get an unused port start from 7007
* [host]: get an ipv4 from eth0(linux) en0(osx)
*
* // create gen-nodejs server
* alias
* processor
* handler
* options
* }
* }
*/
constructor(options) {
// father
super();
options = options || {};
let self = this;
// adapter
self._adapter = new Adapter(options.adapter);
self._adapter.on(EVENT.ERROR, (err) => {
self.emit(EVENT.ERROR, err);
});
self._adapter.on(EVENT.READY, (info) => {
self.emit(EVENT.LOG.INFO, info);
// parser thrift host port
self._host = utils.getLocalIPv4();
options.thrift = _.merge({port: PORT, host: self._host}, options.thrift);
self._host = _.isString(options.thrift.host) ? options.thrift.host : self._host;
self._services = new Map();
utils.getUnusedPort(_.isNumber(options.thrift.port) ? options.thrift.port : PORT)
.then((port) => {
self._port = port;
self._id = self._host + ':' + self._port;
return null;
})
.then(() => {
if (options.thrift.alias && options.thrift.processor && options.thrift.handler) {
self._innerThriftProcessor = options.thrift.processor;
self._innerHandler = options.thrift.handler;
self._serverOptions = options.thrift.options;
self._custom = true;
self.emit(EVENT.LOG.INFO, 'Use use-defined thrift Processor');
} else {
// init thrift handler
self._initThriftHandler();
self.emit(EVENT.LOG.INFO, 'Use inner thrift Processor');
}
return null;
}).then(() => {
// after inital all and start thrift server
self._server = thrift.createServer(self._innerThriftProcessor, self._innerHandler, self._serverOptions || {});
self._server.listen(self._port);
// inital service
if (self._custom) {
return self._publish(options.thrift.alias,
{host: self._host, port: self._port, actions: false},
utils.TTL);
} else {
self.add = self._add;
// inital service
return self._add(options.services);
}
}).then(() => {
// emit listening
self.emit(utils.EVENT.READY, 'ThriftServer ready on ' + self._id);
}).catch((err) => {
self.emit(utils.EVENT.ERROR, err);
});
});
}
/**
* add service or services
* @param {Array|Object} services array - services, object - service, in each handler:
* {
* 1. {String} [alias] // unique, if null, use the hanlder.name or hanlder.identity
* 2. {Object|String} service // service object
* 3. {Array|String} [actions] // permission, if null, allow all service actions, ONLY support PROMISE/SYNC
* *4. {String} [version]
* }
* @return {Promises|bluebird|*}
*/
_add(services) {
if (!this._custom) {
services = utils.trans2Array(services, _.isObject);
return Promises.map(services, (s) => {
// alias/service/actions
let alias = s.alias,
service = s.service,
actions = utils.trans2Array(s.actions, _.isString);
alias = utils.exec((alias) ? alias : (service.name || service.identity));
if (_.isString(alias)) {
let checks = false;
if (!_.isEmpty(actions)) {
checks = {};
actions.forEach((action) => {
if (service && _.isFunction(service[action])) {
checks[action] = true;
} else {
this.emit(utils.EVENT.ERROR, {
err : 'Invalid service or action',
message: 'service: ' + alias + ', action: ' + action
});
}
});
}
// memory
this._services.set(alias, {origin: service, actions: checks});
// public
return this._publish(alias,
{host: this._host, port: this._port, actions: checks}, utils.TTL
).catch((err) => {
this.emit(utils.EVENT.ERROR, {
err : err,
message: 'Publish error, ' + 'service: ' + alias + ', actions: ' + actions
});
});
}
return null;
});
}
return Promises.reject('Disable for this mode');
}
/**
* @returns {ThriftServer.server}
*/
server() {
return this._server;
}
/**
* @returns {ThriftServer.host}
*/
host() {
return this._host;
}
/**
* @returns {ThriftServer.port}
*/
port() {
return this._port;
}
_publish(alias, data, ttl) {
this.emit(EVENT.LOG.INFO, 'Publish service ' + alias + '.' + this._id);
return this._adapter.publish({alias: alias, id: this._id}, data, ttl);
}
/**
* init thrift handler of this
* @private
*/
_initThriftHandler() {
// inner msg handler
let self = this;
this._innerThriftProcessor = Processor;
this._innerHandler = {
call(cmsg, callback) {
// get params
let base = cmsg.base,
caller = cmsg.call,
service = self._services.get(caller.name);
self.emit(EVENT.LOG.DEBUG, 'IN ' + JSON.stringify({
id : base.id, sender: base.sender,
alias: caller.name, action: caller.action, params: caller.params
}));
// set sender
base.sender = self._id;
// handler call
transport.callingHandler(cmsg, service, (err, rmsg) => {
self.emit(EVENT.LOG.DEBUG, 'OUT ' + (err || rmsg.res));
callback(err, rmsg);
});
}
};
}
} |
JavaScript | class NetworkSerializer {
constructor() {
this._builder = pb.loadProtoFile("/resources/protocol/lobby.proto");
this._grtsproto = this._builder.build('grtsproto');
this._protomap = {
/* Receive */
"CONNECTED": this._grtsproto.Connected,
"JOINED_GAME": this._grtsproto.JoinedGame,
"PLAYER_JOINED_GAME": this._grtsproto.PlayerJoinedGame,
"PLAYER_LEFT_GAME": this._grtsproto.PlayerLeftGame,
"PLAYER_CHANGED_LOGIN": this._grtsproto.PlayerChangedLogin,
/* Send */
"CHANGE_LOGIN": this._grtsproto.ChangeLogin,
"LOBBY_READY": this._grtsproto.LobbyReady,
}
}
_getProtoer(context, type) {
let protoer = this._protomap[type];
if (!protoer) {
// TODO: Add a proper log system (CAULIFLOWER? :D)
console.error(`[Serializer:${context}] Cannot find protoer for event type ${message.type}`);
return null;
}
return protoer
}
decode(message) {
message = this._grtsproto.Message.decode(message);
let protoer = this._getProtoer('Decode', message.type)
if (!protoer) { return null; }
message.data = protoer.decode(message.data);
return message;
}
encode(type, data) {
let protoer = this._getProtoer('Decode', type);
if (!protoer) { return null; }
data = new protoer(data);
let message = new this._grtsproto.Message({
'type': type,
'data': data.encode()
})
return message.toBuffer();
}
} |
JavaScript | class Clipboard {
constructor() {
this._setupUI();
// setup events
this._events();
this.currentClipboardData = {};
}
/**
* Caches all the jQuery element queries.
*
* @method _setupUI
* @private
*/
_setupUI() {
var clipboard = $('.cms-clipboard');
this.ui = {
clipboard: clipboard,
triggers: $('.cms-clipboard-trigger a'),
triggerRemove: $('.cms-clipboard-empty a'),
pluginsList: clipboard.find('.cms-clipboard-containers'),
document: $(document)
};
}
/**
* Sets up event handlers for clipboard ui.
*
* @method _events
* @private
*/
_events() {
var that = this;
that.modal = new Modal({
minWidth: MIN_WIDTH,
minHeight: MIN_HEIGHT,
minimizable: false,
maximizable: false,
resizable: false,
closeOnEsc: false
});
Helpers.removeEventListener(
'modal-loaded.clipboard modal-closed.clipboard modal-close.clipboard modal-load.clipboard'
);
Helpers.addEventListener('modal-loaded.clipboard modal-closed.clipboard', (e, { instance }) => {
if (instance === this.modal) {
Plugin._removeAddPluginPlaceholder();
}
});
Helpers.addEventListener('modal-close.clipboard', (e, { instance }) => {
if (instance === this.modal) {
this.ui.pluginsList.prependTo(that.ui.clipboard);
Plugin._updateClipboard();
}
});
Helpers.addEventListener('modal-load.clipboard', (e, { instance }) => {
if (instance === this.modal) {
this.ui.pluginsList.prependTo(that.ui.clipboard);
} else {
this.ui.pluginsList.prependTo(that.ui.clipboard);
Plugin._updateClipboard();
}
});
try {
ls.off(storageKey);
} catch (e) {}
ls.on(storageKey, value => this._handleExternalUpdate(value));
this._toolbarEvents();
}
_toolbarEvents() {
var that = this;
that.ui.triggers.off(Clipboard.click).on(Clipboard.click, function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).parent().hasClass('cms-toolbar-item-navigation-disabled')) {
return false;
}
that.modal.open({
html: that.ui.pluginsList,
title: that.ui.clipboard.data('title'),
width: MIN_WIDTH,
height: MIN_HEIGHT
});
that.ui.document.trigger('click.cms.toolbar');
});
// add remove event
that.ui.triggerRemove.off(Clipboard.click).on(Clipboard.click, function(e) {
e.preventDefault();
e.stopPropagation();
if ($(this).parent().hasClass('cms-toolbar-item-navigation-disabled')) {
return false;
}
that.clear();
});
}
/**
* _handleExternalUpdate
*
* @private
* @param {String} value event new value
*/
_handleExternalUpdate(value) {
var that = this;
var clipboardData = JSON.parse(value);
if (
clipboardData.timestamp < that.currentClipboardData.timestamp ||
(that.currentClipboardData.data &&
that.currentClipboardData.data.plugin_id === clipboardData.data.plugin_id)
) {
that.currentClipboardData = clipboardData;
return;
}
if (!clipboardData.data.plugin_id) {
that._cleanupDOM();
that.currentClipboardData = clipboardData;
return;
}
if (!that.currentClipboardData.data.plugin_id) {
that._enableTriggers();
}
that.ui.pluginsList.html(clipboardData.html);
Plugin._updateClipboard();
CMS._instances.push(new Plugin(`cms-plugin-${clipboardData.data.plugin_id}`, clipboardData.data));
that.currentClipboardData = clipboardData;
}
/**
* @method _isClipboardModalOpen
* @private
* @returns {Boolean}
*/
_isClipboardModalOpen() {
return !!this.modal.ui.modalBody.find('.cms-clipboard-containers').length;
}
/**
* Cleans up DOM state when clipboard is cleared
*
* @method _cleanupDOM
* @private
*/
_cleanupDOM() {
var that = this;
var pasteItems = $('.cms-submenu-item [data-rel=paste]')
.attr('tabindex', '-1')
.parent()
.addClass('cms-submenu-item-disabled');
pasteItems.find('> a').attr('aria-disabled', 'true');
pasteItems.find('.cms-submenu-item-paste-tooltip').css('display', 'none');
pasteItems.find('.cms-submenu-item-paste-tooltip-empty').css('display', 'block');
if (that._isClipboardModalOpen()) {
that.modal.close();
}
that._disableTriggers();
that.ui.document.trigger('click.cms.toolbar');
}
/**
* @method _enableTriggers
* @private
*/
_enableTriggers() {
this.ui.triggers.parent().removeClass('cms-toolbar-item-navigation-disabled');
this.ui.triggerRemove.parent().removeClass('cms-toolbar-item-navigation-disabled');
}
/**
* @method _disableTriggers
* @private
*/
_disableTriggers() {
this.ui.triggers.parent().addClass('cms-toolbar-item-navigation-disabled');
this.ui.triggerRemove.parent().addClass('cms-toolbar-item-navigation-disabled');
}
/**
* Clears the clipboard by quering the server.
* Callback is optional, but if provided - it's called
* no matter what outcome was of the ajax call.
*
* @method clear
* @param {Function} [callback]
*/
clear(callback) {
var that = this;
// post needs to be a string, it will be converted using JSON.parse
var post = '{ "csrfmiddlewaretoken": "' + CMS.config.csrf + '" }';
that._cleanupDOM();
// redirect to ajax
CMS.API.Toolbar.openAjax({
url: Helpers.updateUrlWithPath(CMS.config.clipboard.url),
post: post,
callback: function() {
var args = Array.prototype.slice.call(arguments);
that.populate('', {});
// istanbul ignore next
if (callback) {
callback.apply(this, args);
}
}
});
}
/**
* populate
*
* @public
* @param {String} html markup of the clipboard draggable
* @param {Object} pluginData data of the plugin in the clipboard
*/
populate(html, pluginData) {
this.currentClipboardData = {
data: pluginData,
timestamp: Date.now(),
html: html
};
ls.set(storageKey, JSON.stringify(this.currentClipboardData));
}
} |
JavaScript | class DeveryERC721 extends AbstractSmartContract {
/**
*
* Creates a new instansce of DeveryERC721.
* ```
* // creates a DeveryERC721Client with the default params
* let deveryERC721Client = new DeveryERC721();
*
* //creates a deveryRegistryClient pointing to a custom address
* let deveryERC721Client = new DeveryERC721({address:'0xf17f52151EbEF6C7334FAD080c5704DAAA16b732'});
*
* ```
*
* @param {ClientOptions} options network connection options
*
*/
constructor(options = {
web3Instance: undefined,
acc: undefined,
address: undefined,
walletPrivateKey: undefined,
networkId: undefined,
}) {
super(...arguments);
options = Object.assign(
{
web3Instance: undefined,
acc: undefined,
address: undefined,
walletPrivateKey: undefined,
networkId: undefined,
}
, options,
);
let address = options.address;
let network = options.networkId;
try {
if (!options.web3Instance) {
options.web3Instance = web3;
}
network = options.web3Instance.version.network;
// console.log('it was not possible to find global web3');
} catch (e) {
// console.log('it was not possible to find global web3');
}
if (!network) {
network = options.networkId || 1;
}
if (!address) {
address = deveryERC721Artifact.networks[network].address;
}
this.__deveryERC721Contract = new ethers.Contract(
address, deveryERC721Artifact.abi,
this.__signerOrProvider,
);
this.address = address;
this.abi = deveryERC721Artifact.abi;
}
/**
* This method is used for claiming a product. The method returns you the transaction address of the claim.
* If the product have a maximum mintable quantity set and you try to claim a number of product bigger than the mintable products number set
* the method will not work
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* // Let's log the simplest case of use in the console
*
* deveryErc721Client.claimProduct('0x627306090abaB3A6e1400e9345bC60c78a8BEf57', 1).then(response =>
* console.log('response').catch(err => {
* // treat you error
* })
* )
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
*
* @param {string} productAddress address of the claimed product
* @param {number} quantity quantity of claimed products
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones.
*/
async claimProduct(productAddress, quantity = 1, overrideOptions = {}) {
const result = await this.__deveryERC721Contract
.claimProduct(productAddress, quantity, overrideOptions);
return result.valueOf();
}
// x.__deveryERC721Contract.getApproved
/**
* This method returns you the total amount of approved transactions of the inspected product (referenced by it's token).
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* // Let's log the simplest case of use in the console
*
* deveryErc721Client.getApproved(address).then(response => console.log(`Number of approved transactions ${response}`))
*
* //response is going to be an hexadecimal number representing the amount of approved transactions made with it
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
*
* @param {string} address token address to be inspected.
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones.
*/
async getApproved(address, overrideOptions = {}) {
return await this.__deveryERC721Contract.getApproved(address, overrideOptions);
}
// x.__deveryERC721Contract.getProductsByOwner
/**
* Each brand has a blockchain address.
* This function returns an array with all the product addresses owned by the address passed as a parameter.
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* // Let's log the simplest case of use in the console.
*
* deveryErc721Client.getProductsByOwner(addressOwner).then(response => console.log('these are the products owned by this address', response))
*
* // Since this is a promise function you will need a .then statement to display the result
*
* ```
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {string} addressOwner the blockchain address of whom we want to know the owned tokens
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones
*/
async getProductsByOwner(addressOwner, overrideOptions = {}) {
const result = await this.__deveryERC721Contract
.getProductsByOwner(addressOwner, overrideOptions);
return result.valueOf();
}
/**
*
* Listener for transfer approval events, this event triggers whenever a devery item is transferred in the blockchain.
* Please note that ApprovalEventListeners do not stack, this means that whenever you set one you are
* removing the last one. If you want to remove an ApprovalEventListener, just call this function passing undefined
* as param.
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
*
*
* deveryErc721Client.setApprovalEventListener((brandAccount,appAccount,active) => {
* // whenever an app created we will log it to the console
* console.log(`a brand has been updated ${brandAccount} - ${appAccount} ...`);
* })
*
* // if you want to remove the listener you can simply pass undefined as parameter
*
* deveryErc721Client.setApprovalEventListener(undefined)
*
* // or that is equivalent to the above call
*
*
*
* deveryErc721Client.setApprovalEventListener()
*
*
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {ApprovalEventCallback} callback the callback that will be executed whenever an ApprovalForAll event is
* triggered
*/
setApprovalEventListener(callback) {
const eventName = 'ApprovalForAll'; // @todo: check - may be it should be 'Approval'??
this.__deveryERC721Contract.removeAllListeners(eventName);
if (callback) {
this.__deveryERC721Contract.on(eventName, callback);
}
}
/**
* This is a callback function that will be invoked in response to ApprovalEvents
*
*
* @callback ApprovalEventCallback
* @param {string} productAccount product account address.
* @param {string} brandAccount brand account address.
* @param {string} appAccount application account address.
* @param {string} description description
* @param {boolean} active
*
*/
/**
*
* Listener for transfer approval for all events, this event triggers whenever a devery item is transferred in the blockchain.
* Please note that ApprovalForAllEventListeners do not stack, this means that whenever you set one you are
* removing the last one. If you want to remove an ApprovalForAllEventListener, just call this function passing undefined
* as param.
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
*
*
* deveryErc721Client.setApprovalForAllEventListener((brandAccount,appAccount,active) => {
* // whenever an app created we will log it to the console
* console.log(`a brand has been updated ${brandAccount} - ${appAccount} ...`);
* })
*
* // if you want to remove the listener you can simply pass undefined as parameter
*
* deveryRegistryClient.setApprovalForAllEventListener(undefined)
*
* // or that is equivalent to the above call
*
*
*
* deveryRegistryClient.setApprovalForAllEventListener()
*
*
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
*
* @param {ApprovalEventCallback} callback the callback that will be executed whenever a Approval event is
* triggered
*/
setApprovalForAllEventListener(callback) {
const eventName = 'Approval'; // @todo: check - may be it should be 'ApprovalAll'??
this.__deveryERC721Contract.removeAllListeners(eventName);
if (callback) {
this.__deveryERC721Contract.on(eventName, callback);
}
}
// @todo: re-check callback description
/**
*
* Listener for transfer events, this event triggers whenever a devery item is transferred in the blockchain.
* Please note that TransferEventListeners do not stack, this means that whenever you set one you are
* removing the last one. If you want to remove a TransferEventListener, just call this function passing undefined
* as param.
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
*
*
* deveryErc721Client.setTransferEventListener((brandAccount,appAccount,active) => {
* // whenever an app created we will log it to the console
* console.log(`a brand has been updated ${brandAccount} - ${appAccount} ...`);
* })
*
* // if you want to remove the listener you can simply pass undefined as parameter
*
* deveryErc721Client.setTransferEventListener(undefined)
*
* // or that is equivalent to the above call
*
*
*
* deveryErc721Client.setTransferEventListener()
*
*
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {ApprovalEventCallback} callback the callback that will be executed whenever a Transfer event is
* triggered
*/
setTransferEventListener(callback) {
const eventName = 'Transfer';
this.__deveryERC721Contract.removeAllListeners(eventName);
if (callback) {
this.__deveryERC721Contract.on(eventName, callback);
}
}
/**
*
* Sets the maximum mintable quantity of a given token. *** If you don't set the maximum mintable quantity it will be infinite by default**
*
* @param {string} productAddress The address of the product which the mintable quantity will be set.
* @param {string} quantity the allowed quantity of mintable products.
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones
* @returns {Promise.<Transaction>} a promise that if resolved returns an transaction or raise an error in case of rejection.
*/
async setMaximumMintableQuantity(productAddress, quantity, overrideOptions = {}) {
const result = await this.__deveryERC721Contract
.setMaximumMintableQuantity(productAddress, quantity, overrideOptions);
return result.valueOf();
}
// x.__deveryERC721Contract.tokenIdToProduct
/**
* This method returns the blockchain address of a product, using its token as a parameter.
*
* ***Usage Example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
*
* let deveryErc721Client = new DeveryERC721();
*
* // now you can use it
*
* // to use this function you need to have a token, which can be get through a function like tokenOfOwnerByIndex
* // The token is a hexadecimal number
*
* deveryErc721Client.tokenIdToProduct(tokenId).then(response => console.log('this is your product address', response))
*
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {string} tokenId The token of the product you wish to get the address of.
* @return {Promise.<String>} a promise that if resolved returns a blockchain product address or raise an error in case of rejection.
*
*/
async tokenIdToProduct(tokenId) {
const result = await this.__deveryERC721Contract.tokenIdToProduct(tokenId);
return result.valueOf();
}
/**
* This method returns the (hexadecimal) number of products owned by the account address passed as parameter to the function.
*
* ***Usage Example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
*
* let deveryErc721Client = new DeveryERC721();
*
* // now you can use it
*
* // this method requires an owner address, which can be obtained on the metamask extension by clicking on your account name
*
*
* deveryErc721Client.__deveryERC721Contract.balanceOf(ownerAddress).then(response => console.log('this account owns number of products: ', response))
*
* ```
*
* @param {string} ownerAddress Blockchain address of the inspected account.
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones.
* @return {Promise.<*>} a promise that if resolved returns a hexadecimal number of products or raise an error in case of rejection.
*/
async balanceOf(ownerAddress, overrideOptions = {}) {
const result = await this.__deveryERC721Contract.balanceOf(ownerAddress, overrideOptions);
return result.toNumber();
}
/**
* This method returns the token of a product by its index (it's a position in an array containing all the products owned by the owner address).
*
* ***Usage Example:***
* ```
* // first you need to get a {@link DeveryERC721} instance
*
* let deveryErc721Client = new DeveryERC721();
*
* // now you can use it
*
* deveryErc721Client.__deveryERC721Contract.tokenOfOwnerByIndex(ownerAddress, index).then(response => ( console.log('product token', response)))
*
* // the product order is the same as the array returned by getProductByOwner() . Wherefore the index 0 it's the first address returned by the getProductByOwner method,
* // the index 1 is the second address and so on.
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {string} ownerAddress blockchain address of that we want to know the owned tokens.
* @param {number} index position of the product in the array of all products owned by the account corresponding to the address.
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones
* @return {Promise.<*>} a promise that if resolved returns a token or raise an error in case of rejection.
*/
async tokenOfOwnerByIndex(ownerAddress, index, overrideOptions = {}) {
const result = await this.__deveryERC721Contract
.tokenOfOwnerByIndex(ownerAddress, index, overrideOptions);
return result.toNumber();
}
// x.__deveryERC721Contract.totalAllowedProducts
/**
* This method allows you to query the number of tokens linked to the product address,
* representing the amount of that product generated.
* The response is returned as a hexadecimal number.
*
* ***Usage example:***
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* deveryErc721Client.totalAllowedProducts(productAddress).then(response => {
* console.log(`this is the total amount of products Allowed ${response}`)
* }).catch(err => {
* // handle exceptions here
* })
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
* @param {string} productAddress Blockchain address of the product.
* @return {Promise.<Number>} a promise that if resolved returns number of tokens or raise an error in case of rejection.
*/
async totalAllowedProducts(productAddress) {
const result = await this.__deveryERC721Contract.totalAllowedProducts(productAddress);
return result.toNumber();
}
/**
* You can generate a limited amount of products for each product address.
* If you try to generated more products than you are allowed, this product
* is going to be minted.
* This method returns you the number of minted products for a specific product address.
*
* ***Usage Example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* deveryErc721Client.totalMintedProducts(productAddress).then(response =>
* (console.log('you have the following number of minted products for this address ', response)))
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
*
* @param {string} productAddress inspected product address.
* @return {Promise.<Number>} a promise that if resolved returns number of minted products or raise an error in case of rejection.
*/
async totalMintedProducts(productAddress) {
const result = await this.__deveryERC721Contract.totalMintedProducts(productAddress);
return result.toNumber();
}
/**
* This method transfers the ownership of a claimed product item from one account to another.
* The transfer must be made logged in the account referenced in the 'fromAddress' parameter,
* otherwise the transfer will be denied.
*
* *** Usage Example: ***
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* // now you can use it
*
* deveryErc721Client.safeTransferFrom(fromAddress, toAddress, tokenId).then(transaction => {
* console.log('your transaction was successful');
* // other stuff
* }).catch(err => {
* if(err.message.indexOf('gas required exceeds allowance or always failing transaction') {
* console.log('You do not own the product you are trying to transfer')}
* })
*
* ```
*
* for more info about how to get a {@link DeveryERC721|DeveryERC721 instance click here}.
*
*
* @param {string} fromAddress blockchain address which the transfer is coming from
* @param {string} toAddress blockchain address which the transfer is going to
* @param {string} tokenId Token of the product item being transferred or blockchain address of the product account.
* In case if product address was specified then for transfer is taken the first token (product item)
* of the specified product owned by the fromAddress account.
*/
async safeTransferFrom(fromAddress, toAddress, tokenId) {
if (!/^\d*$/.test(`${tokenId}`)) {
tokenId = await this.getTokenIdByAddress(tokenId, fromAddress);
}
const result = await this
.__deveryERC721Contract['safeTransferFrom(address,address,uint256)'](fromAddress, toAddress, tokenId);
return result.valueOf();
}
async getTokenIdByAddress(address, wallet) {
const balance = await this.balanceOf(wallet);
address = address.toLocaleLowerCase();
for (let i = 0; i < balance; i++) {
// TODO: optimize
const tokenId = await this.tokenOfOwnerByIndex(wallet, i);
const prodAddress = await this.tokenIdToProduct(tokenId);
if (prodAddress.toLocaleLowerCase() === address) {
return tokenId;
}
}
throw new Error('token id not found');
}
/**
* This method creates a devery registry address for the desired contract,
* so the user is able to properly use the devery ERC721 methods.
*
*
* ***Usage example:***
*
* ```
* // first you need to get a {@link DeveryERC721} instance
* let deveryErc721Client = new DeveryERC721();
* //n ow you can use it
*
* // then you have to pass the devery contract method passing the contract as a parameter
* deveryErc721Client.setDeveryRegistryAddress(address).then(transaction => {
* console.log(transaction) }).catch(err => {
* // treat your errors here
* })
* ```
* @param {string} deveryRegistryContractAddress address of the deployed contract.
* @param {TransactionOptions} [overrideOptions] gas options to override the default ones.
*/
async setDeveryRegistryAddress(deveryRegistryContractAddress, overrideOptions = {}) {
const result = await this.__deveryERC721Contract
.setDeveryRegistryAddress(deveryRegistryContractAddress, overrideOptions);
return result.valueOf();
}
/**
* This method returns you whether the account owns tokens of the specified product or not.
* The return of this function is a boolean value.
*
* ***Usage Example***
* ```
* // First you'll need to get a {@link DeveryERC721} instance
*
* let deveryErc721Client = new DeveryERC721();
*
* // Then you will need to pass an account address and a product address as parameters
* deveryErc721Client.hasAccountClaimendProduct(ownerAddress, productAddress)
* .then(hasProduct => console.log(hasProduct))
* .catch(err => {
* //treat errors
* })
* ```
*
* @param {string} ownerAddress Blockchain address of the inspect account
* @param {string} productAddress Blockchain address of the checked product
*/
async hasAccountClaimendProduct(ownerAddress, productAddress) {
const ownedProducts = await this.getProductsByOwner(ownerAddress);
return ownedProducts.includes(productAddress);
}
} |
JavaScript | class Encoder {
constructor() {
}
static wav(bytes, sampleRate, sampleBits, outChannelsNumber) {
let dataLength = bytes.length * (sampleBits / 8);
let buffer = new ArrayBuffer(44 + dataLength);
let data = new DataView(buffer);
let channelCount = outChannelsNumber;
let offset = 0;
let writeString = function(str) {
for (let i = 0; i < str.length; i++) {
data.setUint8(offset + i, str.charCodeAt(i));
}
};
// https://baike.baidu.com/item/WAV
//资源交换文件标志(RIFF)
writeString('RIFF');
offset += 4;
//从下个地址开始到文件尾的总字节数
data.setUint32(offset, 36 + dataLength, true);
offset += 4;
//WAV文件标志(WAVE)
writeString('WAVE');
offset += 4;
//波形格式标志(fmt ),最后一位空格
writeString('fmt ');
offset += 4;
//过滤字节(一般为00000010H),若为00000012H则说明数据头携带附加信息(见“附加信息”)
data.setUint32(offset, 16, true);
offset += 4;
//格式种类(值为1时,表示数据为线性PCM编码)
data.setUint16(offset, 1, true);
offset += 2;
//通道数,单声道为1,双声道为2
data.setUint16(offset, channelCount, true);
offset += 2;
//采样频率
data.setUint32(offset, sampleRate, true);
offset += 4;
//波形数据传输速率(每秒平均字节数)
data.setUint32(offset, channelCount * sampleRate * (sampleBits / 8), true);
offset += 4;
//DATA数据块长度,字节 快数据调整数 采样一次占用字节数 通道数×每样本的数据位数/8
data.setUint16(offset, channelCount * (sampleBits / 8), true);
offset += 2;
//PCM位宽
data.setUint16(offset, sampleBits, true);
offset += 2;
//--------//
//附加信息(可选,由上方过滤字节确定)
//“fact”,该部分是可选部分,一般当WAV文件是由某些软件转换而来时,包含该部分。
//若包含该部分:(1)该部分的前4字节为数据头,一般为4个字母。
//(2)随后4个字节表示长度,即除去头(4字节)和长度(4字节)之后,数据本身的长度。
//(3)最后的字节为数据本身。例如:“66 61 73 74 04 00 00 00F8 2F 14 00” 。
//“66 61 73 74”是fact字段的数据头,“04 00 00 00”是数据本身的长度,“F8 2F 14 00”是数据本身。
//(注意是little-endian字节顺序)
//-------//
//数据标志符(data)
writeString('data');
offset += 4;
//DATA总数据长度字节
data.setUint32(offset, dataLength, true);
offset += 4;
if (sampleBits === 8) {
for (let i = 0; i < bytes.length; i++, offset++) {
let s = Math.max(-1, Math.min(1, bytes[i]));
let val = s < 0 ? s * 0x8000 : s * 0x7FFF;
val = parseInt(255 / (65535 / (val + 32768)));
data.setInt8(offset, val, true);
}
} else {
for (let i = 0; i < bytes.length; i++, offset += 2) {
let s = Math.max(-1, Math.min(1, bytes[i]));
data.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
return data;
}
} |
JavaScript | class JarvisModule {
/**
* Virtual constructor
*/
constructor() {
}
/**
* Virtual initialization function
* @param {JarvisBot} bot - A reference to the current JarvisBot instance
*/
init(bot) { // eslint-disable-line no-unused-vars
}
/**
* Virtual function for loading commands
* @param {JarvisBot} bot - A reference to the current JarvisBot instance
*/
loadCommands(bot) { // eslint-disable-line no-unused-vars
}
} |
JavaScript | class Linter {
/**
*
*/
constructor() {
this.tools = new tools_1.Tools;
}
/**
*
*/
lint(icons) {
this.icons = icons;
return new Promise((resolve, reject) => {
this.resolve = resolve;
this.checkDuplicates();
this.resolve();
});
}
/**
*
*/
checkDuplicates() {
const charStash = [];
const charErrors = [];
const nameStash = [];
const nameErrors = [];
// Loop through each icons
this.icons.forEach((icon) => {
//
if (charStash.indexOf(icon.char) > -1) {
charErrors.push(icon);
}
else {
charStash.push(icon.char);
}
//
if (nameStash.indexOf(icon.name) > -1) {
nameErrors.push(icon);
}
else {
nameStash.push(icon.name);
}
});
this.logDuplicates(charErrors, 'char', 'character keys');
this.logDuplicates(nameErrors, 'name', 'character names');
}
/**
*
*/
logDuplicates(errors, key, title) {
if (errors.length > 0) {
this.tools.softError('Lint error: You have duplicate ' + title + ', please fix');
errors.forEach((icon, index) => {
this.tools.softError('#' + index);
const duplicates = this.icons.filter(item => {
return item[key] === icon[key];
});
duplicates.forEach(err => {
this.tools.softError(`---{ ${err[key]} }---> ${err.path}`);
});
});
process.exit();
}
}
} |
JavaScript | class NgbPaginationEllipsis {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationFirst {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationLast {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationNext {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationNumber {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationPrevious {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPaginationPages {
constructor(templateRef) {
this.templateRef = templateRef;
}
} |
JavaScript | class NgbPagination {
constructor(config) {
this.pageCount = 0;
this.pages = [];
/**
* The current page.
*
* Page numbers start with `1`.
*/
this.page = 1;
/**
* An event fired when the page is changed. Will fire only if collection size is set and all values are valid.
*
* Event payload is the number of the newly selected page.
*
* Page numbers start with `1`.
*/
this.pageChange = new EventEmitter(true);
this.disabled = config.disabled;
this.boundaryLinks = config.boundaryLinks;
this.directionLinks = config.directionLinks;
this.ellipses = config.ellipses;
this.maxSize = config.maxSize;
this.pageSize = config.pageSize;
this.rotate = config.rotate;
this.size = config.size;
}
hasPrevious() { return this.page > 1; }
hasNext() { return this.page < this.pageCount; }
nextDisabled() { return !this.hasNext() || this.disabled; }
previousDisabled() { return !this.hasPrevious() || this.disabled; }
selectPage(pageNumber) { this._updatePages(pageNumber); }
ngOnChanges(changes) { this._updatePages(this.page); }
isEllipsis(pageNumber) { return pageNumber === -1; }
/**
* Appends ellipses and first/last page number to the displayed pages
*/
_applyEllipses(start, end) {
if (this.ellipses) {
if (start > 0) {
// The first page will always be included. If the displayed range
// starts after the third page, then add ellipsis. But if the range
// starts on the third page, then add the second page instead of
// an ellipsis, because the ellipsis would only hide a single page.
if (start > 2) {
this.pages.unshift(-1);
}
else if (start === 2) {
this.pages.unshift(2);
}
this.pages.unshift(1);
}
if (end < this.pageCount) {
// The last page will always be included. If the displayed range
// ends before the third-last page, then add ellipsis. But if the range
// ends on third-last page, then add the second-last page instead of
// an ellipsis, because the ellipsis would only hide a single page.
if (end < (this.pageCount - 2)) {
this.pages.push(-1);
}
else if (end === (this.pageCount - 2)) {
this.pages.push(this.pageCount - 1);
}
this.pages.push(this.pageCount);
}
}
}
/**
* Rotates page numbers based on maxSize items visible.
* Currently selected page stays in the middle:
*
* Ex. for selected page = 6:
* [5,*6*,7] for maxSize = 3
* [4,5,*6*,7] for maxSize = 4
*/
_applyRotation() {
let start = 0;
let end = this.pageCount;
let leftOffset = Math.floor(this.maxSize / 2);
let rightOffset = this.maxSize % 2 === 0 ? leftOffset - 1 : leftOffset;
if (this.page <= leftOffset) {
// very beginning, no rotation -> [0..maxSize]
end = this.maxSize;
}
else if (this.pageCount - this.page < leftOffset) {
// very end, no rotation -> [len-maxSize..len]
start = this.pageCount - this.maxSize;
}
else {
// rotate
start = this.page - leftOffset - 1;
end = this.page + rightOffset;
}
return [start, end];
}
/**
* Paginates page numbers based on maxSize items per page.
*/
_applyPagination() {
let page = Math.ceil(this.page / this.maxSize) - 1;
let start = page * this.maxSize;
let end = start + this.maxSize;
return [start, end];
}
_setPageInRange(newPageNo) {
const prevPageNo = this.page;
this.page = getValueInRange(newPageNo, this.pageCount, 1);
if (this.page !== prevPageNo && isNumber(this.collectionSize)) {
this.pageChange.emit(this.page);
}
}
_updatePages(newPage) {
this.pageCount = Math.ceil(this.collectionSize / this.pageSize);
if (!isNumber(this.pageCount)) {
this.pageCount = 0;
}
// fill-in model needed to render pages
this.pages.length = 0;
for (let i = 1; i <= this.pageCount; i++) {
this.pages.push(i);
}
// set page within 1..max range
this._setPageInRange(newPage);
// apply maxSize if necessary
if (this.maxSize > 0 && this.pageCount > this.maxSize) {
let start = 0;
let end = this.pageCount;
// either paginating or rotating page numbers
if (this.rotate) {
[start, end] = this._applyRotation();
}
else {
[start, end] = this._applyPagination();
}
this.pages = this.pages.slice(start, end);
// adding ellipses
this._applyEllipses(start, end);
}
}
} |
JavaScript | class EntityTypesClient {
/**
* Construct an instance of EntityTypesClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.servicePath] - The domain name of the
* API remote host.
*/
constructor(opts) {
this._descriptors = {};
// Ensure that options include the service address and port.
opts = Object.assign(
{
clientConfig: {},
port: this.constructor.port,
servicePath: this.constructor.servicePath,
},
opts
);
// Create a `gaxGrpc` object, with any grpc-specific options
// sent to the client.
opts.scopes = this.constructor.scopes;
var gaxGrpc = gax.grpc(opts);
// Save the auth object to the client, for use by other methods.
this.auth = gaxGrpc.auth;
// Determine the client header string.
var clientHeader = [
`gl-node/${process.version.node}`,
`grpc/${gaxGrpc.grpcVersion}`,
`gax/${gax.version}`,
`gapic/${VERSION}`,
];
if (opts.libName && opts.libVersion) {
clientHeader.push(`${opts.libName}/${opts.libVersion}`);
}
// Load the applicable protos.
var protos = merge(
{},
gaxGrpc.loadProto(
path.join(__dirname, '..', '..', 'protos'),
'google/cloud/dialogflow/v2beta1/entity_type.proto'
)
);
// This API contains "path templates"; forward-slash-separated
// identifiers to uniquely identify resources within the API.
// Create useful helper objects for these.
this._pathTemplates = {
projectAgentPathTemplate: new gax.PathTemplate(
'projects/{project}/agent'
),
entityTypePathTemplate: new gax.PathTemplate(
'projects/{project}/agent/entityTypes/{entity_type}'
),
};
// Some of the methods on this service return "paged" results,
// (e.g. 50 results at a time, with tokens to get subsequent
// pages). Denote the keys used for pagination and results.
this._descriptors.page = {
listEntityTypes: new gax.PageDescriptor(
'pageToken',
'nextPageToken',
'entityTypes'
),
};
var protoFilesRoot = new gax.grpc.GoogleProtoFilesRoot();
protoFilesRoot = protobuf.loadSync(
path.join(
__dirname,
'..',
'..',
'protos',
'google/cloud/dialogflow/v2beta1/entity_type.proto'
),
protoFilesRoot
);
// This API contains "long-running operations", which return a
// an Operation object that allows for tracking of the operation,
// rather than holding a request open.
this.operationsClient = new gax.lro({
auth: gaxGrpc.auth,
grpc: gaxGrpc.grpc,
}).operationsClient(opts);
var batchUpdateEntityTypesResponse = protoFilesRoot.lookup(
'google.cloud.dialogflow.v2beta1.BatchUpdateEntityTypesResponse'
);
var batchUpdateEntityTypesMetadata = protoFilesRoot.lookup(
'google.protobuf.Struct'
);
var batchDeleteEntityTypesResponse = protoFilesRoot.lookup(
'google.protobuf.Empty'
);
var batchDeleteEntityTypesMetadata = protoFilesRoot.lookup(
'google.protobuf.Struct'
);
var batchCreateEntitiesResponse = protoFilesRoot.lookup(
'google.protobuf.Empty'
);
var batchCreateEntitiesMetadata = protoFilesRoot.lookup(
'google.protobuf.Struct'
);
var batchUpdateEntitiesResponse = protoFilesRoot.lookup(
'google.protobuf.Empty'
);
var batchUpdateEntitiesMetadata = protoFilesRoot.lookup(
'google.protobuf.Struct'
);
var batchDeleteEntitiesResponse = protoFilesRoot.lookup(
'google.protobuf.Empty'
);
var batchDeleteEntitiesMetadata = protoFilesRoot.lookup(
'google.protobuf.Struct'
);
this._descriptors.longrunning = {
batchUpdateEntityTypes: new gax.LongrunningDescriptor(
this.operationsClient,
batchUpdateEntityTypesResponse.decode.bind(
batchUpdateEntityTypesResponse
),
batchUpdateEntityTypesMetadata.decode.bind(
batchUpdateEntityTypesMetadata
)
),
batchDeleteEntityTypes: new gax.LongrunningDescriptor(
this.operationsClient,
batchDeleteEntityTypesResponse.decode.bind(
batchDeleteEntityTypesResponse
),
batchDeleteEntityTypesMetadata.decode.bind(
batchDeleteEntityTypesMetadata
)
),
batchCreateEntities: new gax.LongrunningDescriptor(
this.operationsClient,
batchCreateEntitiesResponse.decode.bind(batchCreateEntitiesResponse),
batchCreateEntitiesMetadata.decode.bind(batchCreateEntitiesMetadata)
),
batchUpdateEntities: new gax.LongrunningDescriptor(
this.operationsClient,
batchUpdateEntitiesResponse.decode.bind(batchUpdateEntitiesResponse),
batchUpdateEntitiesMetadata.decode.bind(batchUpdateEntitiesMetadata)
),
batchDeleteEntities: new gax.LongrunningDescriptor(
this.operationsClient,
batchDeleteEntitiesResponse.decode.bind(batchDeleteEntitiesResponse),
batchDeleteEntitiesMetadata.decode.bind(batchDeleteEntitiesMetadata)
),
};
// Put together the default options sent with requests.
var defaults = gaxGrpc.constructSettings(
'google.cloud.dialogflow.v2beta1.EntityTypes',
gapicConfig,
opts.clientConfig,
{'x-goog-api-client': clientHeader.join(' ')}
);
// Set up a dictionary of "inner API calls"; the core implementation
// of calling the API is handled in `google-gax`, with this code
// merely providing the destination and request information.
this._innerApiCalls = {};
// Put together the "service stub" for
// google.cloud.dialogflow.v2beta1.EntityTypes.
var entityTypesStub = gaxGrpc.createStub(
protos.google.cloud.dialogflow.v2beta1.EntityTypes,
opts
);
// Iterate over each of the methods that the service provides
// and create an API call method for each.
var entityTypesStubMethods = [
'listEntityTypes',
'getEntityType',
'createEntityType',
'updateEntityType',
'deleteEntityType',
'batchUpdateEntityTypes',
'batchDeleteEntityTypes',
'batchCreateEntities',
'batchUpdateEntities',
'batchDeleteEntities',
];
for (let methodName of entityTypesStubMethods) {
this._innerApiCalls[methodName] = gax.createApiCall(
entityTypesStub.then(
stub =>
function() {
var args = Array.prototype.slice.call(arguments, 0);
return stub[methodName].apply(stub, args);
}
),
defaults[methodName],
this._descriptors.page[methodName] ||
this._descriptors.longrunning[methodName]
);
}
}
/**
* The DNS address for this API service.
*/
static get servicePath() {
return 'dialogflow.googleapis.com';
}
/**
* The port for this API service.
*/
static get port() {
return 443;
}
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static get scopes() {
return ['https://www.googleapis.com/auth/cloud-platform'];
}
/**
* Return the project ID used by this class.
* @param {function(Error, string)} callback - the callback to
* be called with the current project Id.
*/
getProjectId(callback) {
return this.auth.getProjectId(callback);
}
// -------------------
// -- Service calls --
// -------------------
/**
* Returns the list of all entity types in the specified agent.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The agent to list all entity types from.
* Format: `projects/<Project ID>/agent`.
* @param {string} [request.languageCode]
* Optional. The language to list entity synonyms for. If not specified,
* the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {number} [request.pageSize]
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Array, ?Object, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
*
* When autoPaginate: false is specified through options, it contains the result
* in a single response. If the response indicates the next page exists, the third
* parameter is set to be used for the next request object. The fourth parameter keeps
* the raw response object of an object representing [ListEntityTypesResponse]{@link google.cloud.dialogflow.v2beta1.ListEntityTypesResponse}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType} in a single response.
* The second element is the next request object if the response
* indicates the next page exists, or null. The third element is
* an object representing [ListEntityTypesResponse]{@link google.cloud.dialogflow.v2beta1.ListEntityTypesResponse}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* // Iterate over all elements.
* var formattedParent = client.projectAgentPath('[PROJECT]');
*
* client.listEntityTypes({parent: formattedParent})
* .then(responses => {
* var resources = responses[0];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i])
* }
* })
* .catch(err => {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var formattedParent = client.projectAgentPath('[PROJECT]');
*
*
* var options = {autoPaginate: false};
* var callback = responses => {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows that there are more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (let i = 0; i < resources.length; i += 1) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listEntityTypes(nextRequest, options).then(callback);
* }
* }
* client.listEntityTypes({parent: formattedParent}, options)
* .then(callback)
* .catch(err => {
* console.error(err);
* });
*/
listEntityTypes(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.listEntityTypes(request, options, callback);
}
/**
* Equivalent to {@link listEntityTypes}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listEntityTypes} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The agent to list all entity types from.
* Format: `projects/<Project ID>/agent`.
* @param {string} [request.languageCode]
* Optional. The language to list entity synonyms for. If not specified,
* the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {number} [request.pageSize]
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @returns {Stream}
* An object stream which emits an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType} on 'data' event.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
* client.listEntityTypesStream({parent: formattedParent})
* .on('data', element => {
* // doThingsWith(element)
* }).on('error', err => {
* console.log(err);
* });
*/
listEntityTypesStream(request, options) {
options = options || {};
return this._descriptors.page.listEntityTypes.createStream(
this._innerApiCalls.listEntityTypes,
request,
options
);
}
/**
* Retrieves the specified entity type.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The name of the entity type.
* Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
* @param {string} [request.languageCode]
* Optional. The language to retrieve entity synonyms for. If not specified,
* the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedName = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* client.getEntityType({name: formattedName})
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
getEntityType(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.getEntityType(request, options, callback);
}
/**
* Creates an entity type in the specified agent.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The agent to create a entity type for.
* Format: `projects/<Project ID>/agent`.
* @param {Object} request.entityType
* Required. The entity type to create.
*
* This object should have the same structure as [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entity_type`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
* var entityType = {};
* var request = {
* parent: formattedParent,
* entityType: entityType,
* };
* client.createEntityType(request)
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
createEntityType(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.createEntityType(request, options, callback);
}
/**
* Updates the specified entity type.
*
* @param {Object} request
* The request object that will be sent.
* @param {Object} request.entityType
* Required. The entity type to update.
* Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
*
* This object should have the same structure as [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entity_type`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [request.updateMask]
* Optional. The mask to control which fields get updated.
*
* This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [EntityType]{@link google.cloud.dialogflow.v2beta1.EntityType}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var entityType = {};
* client.updateEntityType({entityType: entityType})
* .then(responses => {
* var response = responses[0];
* // doThingsWith(response)
* })
* .catch(err => {
* console.error(err);
* });
*/
updateEntityType(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.updateEntityType(request, options, callback);
}
/**
* Deletes the specified entity type.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* Required. The name of the entity type to delete.
* Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)} [callback]
* The function which will be called with the result of the API call.
* @returns {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedName = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* client.deleteEntityType({name: formattedName}).catch(err => {
* console.error(err);
* });
*/
deleteEntityType(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.deleteEntityType(request, options, callback);
}
/**
* Updates/Creates multiple entity types in the specified agent.
*
* Operation <response: BatchUpdateEntityTypesResponse,
* metadata: google.protobuf.Struct>
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The name of the agent to update or create entity types in.
* Format: `projects/<Project ID>/agent`.
* @param {string} [request.entityTypeBatchUri]
* The URI to a Google Cloud Storage file containing entity types to update
* or create. The file format can either be a serialized proto (of
* EntityBatch type) or a JSON object. Note: The URI must start with
* "gs://".
* @param {Object} [request.entityTypeBatchInline]
* The collection of entity type to update or create.
*
* This object should have the same structure as [EntityTypeBatch]{@link google.cloud.dialogflow.v2beta1.EntityTypeBatch}
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entity_types`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [request.updateMask]
* Optional. The mask to control which fields get updated.
*
* This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
*
* // Handle the operation using the promise pattern.
* client.batchUpdateEntityTypes({parent: formattedParent})
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
*
* // Handle the operation using the event emitter pattern.
* client.batchUpdateEntityTypes({parent: formattedParent})
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
batchUpdateEntityTypes(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.batchUpdateEntityTypes(
request,
options,
callback
);
}
/**
* Deletes entity types in the specified agent.
*
* Operation <response: google.protobuf.Empty,
* metadata: google.protobuf.Struct>
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The name of the agent to delete all entities types for. Format:
* `projects/<Project ID>/agent`.
* @param {string[]} request.entityTypeNames
* Required. The names entity types to delete. All names must point to the
* same agent as `parent`.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
* var entityTypeNames = [];
* var request = {
* parent: formattedParent,
* entityTypeNames: entityTypeNames,
* };
*
* // Handle the operation using the promise pattern.
* client.batchDeleteEntityTypes(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.projectAgentPath('[PROJECT]');
* var entityTypeNames = [];
* var request = {
* parent: formattedParent,
* entityTypeNames: entityTypeNames,
* };
*
* // Handle the operation using the event emitter pattern.
* client.batchDeleteEntityTypes(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
batchDeleteEntityTypes(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.batchDeleteEntityTypes(
request,
options,
callback
);
}
/**
* Creates multiple new entities in the specified entity type (extends the
* existing collection of entries).
*
* Operation <response: google.protobuf.Empty>
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The name of the entity type to create entities in. Format:
* `projects/<Project ID>/agent/entityTypes/<Entity Type ID>`.
* @param {Object[]} request.entities
* Required. The collection of entities to create.
*
* This object should have the same structure as [Entity]{@link google.cloud.dialogflow.v2beta1.Entity}
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entities`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entities = [];
* var request = {
* parent: formattedParent,
* entities: entities,
* };
*
* // Handle the operation using the promise pattern.
* client.batchCreateEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entities = [];
* var request = {
* parent: formattedParent,
* entities: entities,
* };
*
* // Handle the operation using the event emitter pattern.
* client.batchCreateEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
batchCreateEntities(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.batchCreateEntities(request, options, callback);
}
/**
* Updates entities in the specified entity type (replaces the existing
* collection of entries).
*
* Operation <response: google.protobuf.Empty,
* metadata: google.protobuf.Struct>
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The name of the entity type to update the entities in. Format:
* `projects/<Project ID>/agent/entityTypes/<Entity Type ID>`.
* @param {Object[]} request.entities
* Required. The collection of new entities to replace the existing entities.
*
* This object should have the same structure as [Entity]{@link google.cloud.dialogflow.v2beta1.Entity}
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entities`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [request.updateMask]
* Optional. The mask to control which fields get updated.
*
* This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask}
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entities = [];
* var request = {
* parent: formattedParent,
* entities: entities,
* };
*
* // Handle the operation using the promise pattern.
* client.batchUpdateEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entities = [];
* var request = {
* parent: formattedParent,
* entities: entities,
* };
*
* // Handle the operation using the event emitter pattern.
* client.batchUpdateEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
batchUpdateEntities(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.batchUpdateEntities(request, options, callback);
}
/**
* Deletes entities in the specified entity type.
*
* Operation <response: google.protobuf.Empty,
* metadata: google.protobuf.Struct>
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. The name of the entity type to delete entries for. Format:
* `projects/<Project ID>/agent/entityTypes/<Entity Type ID>`.
* @param {string[]} request.entityValues
* Required. The canonical `values` of the entities to delete. Note that
* these are not fully-qualified names, i.e. they don't start with
* `projects/<Project ID>`.
* @param {string} [request.languageCode]
* Optional. The language of entity synonyms defined in `entities`. If not
* specified, the agent's default language is used.
* [More than a dozen
* languages](https://dialogflow.com/docs/reference/language) are supported.
* Note: languages must be enabled in the agent, before they can be used.
* @param {Object} [options]
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)} [callback]
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* @returns {Promise} - The promise which resolves to an array.
* The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/Operation} object.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* const dialogflow = require('dialogflow.v2beta1');
*
* var client = new dialogflow.v2beta1.EntityTypesClient({
* // optional auth parameters.
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entityValues = [];
* var request = {
* parent: formattedParent,
* entityValues: entityValues,
* };
*
* // Handle the operation using the promise pattern.
* client.batchDeleteEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Operation#promise starts polling for the completion of the LRO.
* return operation.promise();
* })
* .then(responses => {
* // The final result of the operation.
* var result = responses[0];
*
* // The metadata value of the completed operation.
* var metadata = responses[1];
*
* // The response of the api call returning the complete operation.
* var finalApiResponse = responses[2];
* })
* .catch(err => {
* console.error(err);
* });
*
* var formattedParent = client.entityTypePath('[PROJECT]', '[ENTITY_TYPE]');
* var entityValues = [];
* var request = {
* parent: formattedParent,
* entityValues: entityValues,
* };
*
* // Handle the operation using the event emitter pattern.
* client.batchDeleteEntities(request)
* .then(responses => {
* var operation = responses[0];
* var initialApiResponse = responses[1];
*
* // Adding a listener for the "complete" event starts polling for the
* // completion of the operation.
* operation.on('complete', (result, metadata, finalApiResponse) => {
* // doSomethingWith(result);
* });
*
* // Adding a listener for the "progress" event causes the callback to be
* // called on any change in metadata when the operation is polled.
* operation.on('progress', (metadata, apiResponse) => {
* // doSomethingWith(metadata)
* });
*
* // Adding a listener for the "error" event handles any errors found during polling.
* operation.on('error', err => {
* // throw(err);
* });
* })
* .catch(err => {
* console.error(err);
* });
*/
batchDeleteEntities(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
return this._innerApiCalls.batchDeleteEntities(request, options, callback);
}
// --------------------
// -- Path templates --
// --------------------
/**
* Return a fully-qualified project_agent resource name string.
*
* @param {String} project
* @returns {String}
*/
projectAgentPath(project) {
return this._pathTemplates.projectAgentPathTemplate.render({
project: project,
});
}
/**
* Return a fully-qualified entity_type resource name string.
*
* @param {String} project
* @param {String} entityType
* @returns {String}
*/
entityTypePath(project, entityType) {
return this._pathTemplates.entityTypePathTemplate.render({
project: project,
entity_type: entityType,
});
}
/**
* Parse the projectAgentName from a project_agent resource.
*
* @param {String} projectAgentName
* A fully-qualified path representing a project_agent resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromProjectAgentName(projectAgentName) {
return this._pathTemplates.projectAgentPathTemplate.match(projectAgentName)
.project;
}
/**
* Parse the entityTypeName from a entity_type resource.
*
* @param {String} entityTypeName
* A fully-qualified path representing a entity_type resources.
* @returns {String} - A string representing the project.
*/
matchProjectFromEntityTypeName(entityTypeName) {
return this._pathTemplates.entityTypePathTemplate.match(entityTypeName)
.project;
}
/**
* Parse the entityTypeName from a entity_type resource.
*
* @param {String} entityTypeName
* A fully-qualified path representing a entity_type resources.
* @returns {String} - A string representing the entity_type.
*/
matchEntityTypeFromEntityTypeName(entityTypeName) {
return this._pathTemplates.entityTypePathTemplate.match(entityTypeName)
.entity_type;
}
} |
JavaScript | class EventEmitter {
getType() {
}
isStateCompatible(state) {
}
start(initial) {
// starts generating timer
// if initial then emit on start
if (initial) {
this.trigger();
}
}
increase() {
// transition in this state
// increase frequency
}
decrease() {
// transition out of this state
// decrease frequency
}
notifyMovementChange(isMoving) {
}
stop() {
// stops generating timer
}
dispose() {
// stops timer
// deletes all characters/environments
}
trigger() {
// creates character/environment
}
} |
JavaScript | class Bower {
/**
* Clean up (rm -rf) the local Bower working area.
* This deletes the installs for this directory, not the Bower cache
* (usually stored in ~/.cache/bower).
* @return {Promise} A promise handling the prune operation.
*/
prune() {
return new Promise((resolve, reject) => {
Ana.log("bower/prune");
childProcess.exec("rm -rf bower_components", function(err) {
if (err) {
Ana.fail("bower/prune");
reject({retry: true, error: err});
} else {
Ana.success("bower/prune");
resolve();
}
});
});
}
/**
* Installs the specified Bower package and analyses it for main html files in the bower.json,
* returning a list of them via the promise.
* @param {string} owner - the package owner
* @param {string} repo - the package repository name
* @param {string} versionOrSha - the package version code or sha
* @return {Promise} a promise, returning a list of main html files found.
*/
install(owner, repo, versionOrSha) {
var packageWithOwner = owner + "/" + repo;
var packageToInstall = packageWithOwner + "#" + versionOrSha;
Ana.log("bower/install", packageToInstall);
return new Promise((resolve, reject) => {
bower.commands.install([packageToInstall], {}, {force: false}).on('end', function(installed) {
Ana.success("bower/install", packageToInstall);
for (let bowerPackage in installed) {
if (installed[bowerPackage].endpoint.source.toLowerCase() != packageWithOwner.toLowerCase()) {
// Skip over dependencies (we're not interested in them)
continue;
}
var canonicalDir = installed[bowerPackage].canonicalDir;
var mainHtmls = installed[bowerPackage].pkgMeta.main;
if (!mainHtmls) {
// TODO: Look in the directory and see what .html files we might be able to consume.
Ana.log("bower/install", "Couldn't find main.html after installing", packageToInstall);
resolve([]);
return;
}
if (!Array.isArray(mainHtmls)) {
mainHtmls = [mainHtmls];
}
resolve({root: canonicalDir, mainHtmls: mainHtmls});
return;
}
Ana.fail("bower/install", "Couldn't find package after installing [", packageToInstall, "] found [" + JSON.stringify(installed) + "]");
reject(Error("BOWER: install: package installed not in list"));
}).on('error', function(error) {
Ana.fail("bower/install", packageToInstall);
var retry = true;
if (error.code && fatalErrorCodes.indexOf(error.code) != -1 || error instanceof TypeError) {
retry = false;
}
reject({retry: retry, error: error});
});
});
}
/**
* Gathers transitive runtime dependencies for the given package as well as the
* declared development dependencies (but not their dependencies).
* The dependency list gathered should be enough to run any demos for the given
* package.
* Dependencies look like {name:string, owner:string, repo:string, version:string}.
* @param {string} owner - the package owner
* @param {string} repo - the package repository name
* @param {string} versionOrSha - the package version code or sha
* @return {Promise.<Array.<object>>} a promise, returning a list of dependency objects.
*/
findDependencies(owner, repo, versionOrSha) {
var ownerPackageVersionString = owner + "/" + repo + "#" + versionOrSha;
Ana.log("bower/findDependencies", ownerPackageVersionString);
// The Bower API is pretty annoying. Unless the results are cached it will not reliably
// report the github tag that it used to download the correct dependencies. In order
// to make it do what we want, we need to do two dependency walks - one (online) to
// populate the cache and another (offline) to gather the results.
return Bower.dependencies(ownerPackageVersionString, {}, false, ['empty-buddy']).then(() => {
return Bower.dependencies(ownerPackageVersionString, {}, false, ['empty-buddy']);
});
}
static dependencies(ownerPackageVersionString, processed, offline, pairBuddy) {
return Bower.infoPromise(ownerPackageVersionString, offline, pairBuddy).then(info => {
// Gather all of the dependencies we want to look at.
var depsToProcess =
Object.assign(info.dependencies ? info.dependencies : {},
Object.keys(processed).length == 0 && info.devDependencies ? info.devDependencies : {});
// Filter out what we've already processed.
Object.keys(depsToProcess).forEach(key => {
if (processed[key]) {
delete depsToProcess[key];
}
});
var result = info.metadata ? [info.metadata] : [];
var keys = Object.keys(depsToProcess);
if (!keys.length) {
return result;
}
// Analyse all of the dependencies we have left.
var promises = [];
keys.forEach(key => {
processed[key] = key;
var packageToProcess = depsToProcess[key];
/*
Many packages are in package:semver format (also package:package#semver package:owner/package#semver)
Sadly, many of the 'semver's in Bower are just not matched by any semver parsers. It seems that Bower
is extremely tolerant, so we must be too. However, this is hard! (eg 'bower install q#x' is fine)
Rather than parsing or validating semvers, we'll just try a couple of versions of each package.
*/
// pairBuddy collects the errors from each install.
// We use it to determine whether a genuine error occured (two failures).
var pairBuddy = [];
var keyPlusPackageToProcess;
if (packageToProcess.indexOf('#') == 0) {
keyPlusPackageToProcess = key + packageToProcess;
} else {
keyPlusPackageToProcess = key + "#" + packageToProcess;
}
promises.push(Bower.dependencies(keyPlusPackageToProcess, processed, offline, pairBuddy));
promises.push(Bower.dependencies(packageToProcess, processed, offline, pairBuddy));
});
return Promise.all(promises).then(dependencyList => [].concat.apply(result, dependencyList));
});
}
static infoPromise(ownerPackageVersionString, offline, pairBuddy) {
var ownerRepo = function(resolverSource) {
var source = url.parse(resolverSource);
if (source.hostname != 'github.com')
return null;
var parts = source.pathname.substring(1).split('/', 2);
var owner = parts[0];
var repo = parts[1];
repo = repo.replace(/\.git$/, '');
return {'owner': owner, 'repo': repo};
};
return new Promise(resolve => {
var metadata = null;
bower.commands.info(
ownerPackageVersionString.indexOf("git://") == 0 ? ownerPackageVersionString : ownerPackageVersionString.toLowerCase(),
undefined /* property */,
{
offline: offline
}
).on('end', function(info) {
// For anything with an unspecified version, the result from bower may be
// an unspecified list. Choose the latest.
var result = info.latest ? info.latest : info;
result.metadata = metadata;
resolve(result);
}).on('error', function(error) {
pairBuddy.push(error);
if (pairBuddy.length == 2) {
// Oh NOES! Neither pair attempt made it. This dependency was actually probably bad! :(
Ana.fail("bower/findDependencies/info");
Ana.log("bower/findDependencies/info failure info %s: %s", ownerPackageVersionString, pairBuddy);
}
resolve({});
}).on('log', function(logEntry) {
if (logEntry.id == 'cached' && logEntry.data && logEntry.data.pkgMeta &&
logEntry.data.pkgMeta._resolution) {
metadata = ownerRepo(logEntry.data.resolver.source);
if (metadata == null)
return;
metadata.version = logEntry.data.pkgMeta._resolution.tag || logEntry.data.pkgMeta._resolution.commit;
metadata.name = logEntry.data.pkgMeta.name;
} else if (logEntry.id == 'not-cached' && metadata == null) {
// Only use these values if we have no other choice...
metadata = ownerRepo(logEntry.data.resolver.source);
if (metadata == null)
return;
metadata.version = logEntry.data.resolver.target;
metadata.name = logEntry.data.resolver.name;
}
});
});
}
} |
JavaScript | class App extends Component {
state = {
parties: []
}
componentDidMount() {
axios.get('https://party-planner-build-week.herokuapp.com/api/parties')
.then(res => {this.setState({parties: res.data}) })
.catch(err => console.log(err));
}
addParties = (e, party) => {
console.log('party', party)
axios
.post('https://party-planner-build-week.herokuapp.com/api/parties', party)
.then(res => {
console.log('add parties', res.data)
this.setState({ parties: [...this.state.parties, res.data] })
})
.catch(err => {
console.log(err)
})
}
// addParties = event => {
// event.preventDefault();
// axios
// .post('https://party-planner-build-week.herokuapp.com/api/parties', this.state)
// .then(res => {
// console.log(res)
// window.location.reload();
// })
// .catch(err => {
// console.log(err)
// })
// this.setState({
// party: {
// theme: '',
// date: '',
// budget: 0,
// guestCount: 0
// }
// })
// }
deleteParties = (e, id) => {
e.preventDefault();
axios
.delete(`https://party-planner-build-week.herokuapp.com/api/parties/${id}`)
.then(res => {
})
.catch(err => console.log(err))
}
render() {
return (
<div className="App">
<NavLink to="/partyForm" className="navLink">
party form
</NavLink>
<NavLink to="/partyList" className="navLink">
party list
</NavLink>
{/* <NavLink to="/shoppingList" className="navLink">
shopping List
</NavLink>
<NavLink to="/todoList" className="navLink">
todo list
</NavLink> */}
<Route path="/" component={ModalContainer} />
<Route path="/register" component={SignUpPage} />
{/* <Route path="/partyList" component={PartyList} parties={this.state.parties} /> */}
<Route path="/partyForm" render={props => ( <PartyForm {...props} addParties={this.addParties} />)} />
<Route path="/api/parties/:id" render={props => ( <PartyView {...props} /> )} />
{/* <Route path="/parties" render={props => ( <TodoList {...props} addParties={this.addParties} /> )} /> */}
<Route path="/shoppingList" render={props => ( <ShoppingList {...props} />)} />
<Route path="/partyList" render={props => ( <PartyList {...props} {...this.state} parties={this.state.parties} />)} />
</div>
);
}
} |
JavaScript | class FilterRect extends React.Component {
state = {
color: 'green'
};
componentDidMount() {
this.applyCache();
}
handleClick = () => {
this.setState(
{
color: Konva.Util.getRandomColor()
},
() => {
// recache shape when we updated it
this.applyCache();
}
);
};
applyCache() {
this.rect.cache();
this.rect.getLayer().batchDraw();
}
render() {
return (
<Rect
filters={[Konva.Filters.Noise]}
noise={1}
x={200}
y={10}
width={50}
height={50}
fill={this.state.color}
shadowBlur={10}
ref={node => {
this.rect = node;
}}
onClick={this.handleClick}
/>
);
}
} |
JavaScript | class Keyboard {
/**
* The Game Keyboard constructor
* @param {Display} display
* @param {Scores} scores
* @param {Object} shortcuts
* @returns {Void}
*/
constructor(display, scores, shortcuts) {
this.shortcuts = shortcuts;
this.keyPressed = null;
this.display = display;
this.scores = scores;
document.addEventListener("keydown", e => this.onKeyDown(e));
document.addEventListener("keyup", e => this.onKeyUp(e));
}
/**
* Key handler for the on key down event
* @param {Event} event
* @returns {Void}
*/
onKeyDown(event) {
if (this.display.isPlaying && KeyCode.isFastKey(event.keyCode)) {
if (this.keyPressed === null) {
this.keyPressed = event.keyCode;
} else {
return;
}
}
this.pressKey(event.keyCode, event);
}
/**
* Key handler for the on key up event
* @returns {Void}
*/
onKeyUp() {
this.keyPressed = null;
}
/**
* When a key is pressed, this is called on each frame for fast key movements
* @returns {Void}
*/
onKeyHold() {
if (this.keyPressed !== null && this.display.isPlaying) {
this.pressKey(this.keyPressed);
}
}
/**
* Key Press Event
* @param {Number} key
* @param {?Event} event
* @returns {Void}
*/
pressKey(key, event) {
const keyCode = KeyCode.keyToCode(key);
let shortcut = "";
if (this.scores.isFocused) {
if (KeyCode.isEnter(key)) {
this.shortcuts.gameOver.O();
}
} else {
if (!this.display.isPlaying) {
event.preventDefault();
}
if ([ "E", "1", "Numpad1" ].includes(keyCode)) {
shortcut = "E";
} else if ([ "R", "2", "Numpad2" ].includes(keyCode)) {
shortcut = "R";
} else if ([ "K", "3", "Numpad3" ].includes(keyCode)) {
shortcut = "C";
} else if ([ "Enter", "Return", "Space", "O" ].includes(keyCode)) {
shortcut = "O";
} else if (KeyCode.isErase(key)) {
shortcut = "B";
} else if (KeyCode.isPauseContinue(key)) {
shortcut = "P";
} else if (KeyCode.isLeft(key)) {
shortcut = "A";
} else if (KeyCode.isRight(key)) {
shortcut = "D";
} else {
shortcut = keyCode;
}
if (this.shortcuts[this.display.get()][shortcut]) {
this.shortcuts[this.display.get()][shortcut]();
}
}
}
} |
JavaScript | class Amplitude {
constructor(smoothing) {
// Set to 2048 for now. In future iterations, this should be inherited or parsed from p5sound's default
this.bufferSize = safeBufferSize(2048);
// set audio context
this.audiocontext = p5sound.audiocontext;
this._workletNode = new AudioWorkletNode(
this.audiocontext,
processorNames.amplitudeProcessor,
{
outputChannelCount: [1],
parameterData: { smoothing: smoothing || 0 },
processorOptions: {
normalize: false,
smoothing: smoothing || 0,
numInputChannels: 2,
bufferSize: this.bufferSize,
},
}
);
this._workletNode.port.onmessage = function (event) {
if (event.data.name === 'amplitude') {
this.volume = event.data.volume;
this.volNorm = event.data.volNorm;
this.stereoVol = event.data.stereoVol;
this.stereoVolNorm = event.data.stereoVolNorm;
}
}.bind(this);
// for connections
this.input = this._workletNode;
this.output = this.audiocontext.createGain();
// the variables to return
this.volume = 0;
this.volNorm = 0;
this.stereoVol = [0, 0];
this.stereoVolNorm = [0, 0];
this.normalize = false;
this._workletNode.connect(this.output);
this.output.gain.value = 0;
// this may only be necessary because of a Chrome bug
this.output.connect(this.audiocontext.destination);
// connect to p5sound main output by default, unless set by input()
p5sound.meter.connect(this._workletNode);
// add this p5.SoundFile to the soundArray
p5sound.soundArray.push(this);
}
/**
* Connects to the p5sound instance (main output) by default.
* Optionally, you can pass in a specific source (i.e. a soundfile).
*
* @method setInput
* @for p5.Amplitude
* @param {soundObject|undefined} [snd] set the sound source
* (optional, defaults to
* main output)
* @param {Number|undefined} [smoothing] a range between 0.0 and 1.0
* to smooth amplitude readings
* @example
* <div><code>
* function preload(){
* sound1 = loadSound('assets/beat.mp3');
* sound2 = loadSound('assets/drum.mp3');
* }
* function setup(){
* cnv = createCanvas(100, 100);
* cnv.mouseClicked(toggleSound);
*
* amplitude = new p5.Amplitude();
* amplitude.setInput(sound2);
* }
*
* function draw() {
* background(220);
* text('tap to play', 20, 20);
*
* let level = amplitude.getLevel();
* let size = map(level, 0, 1, 0, 200);
* ellipse(width/2, height/2, size, size);
* }
*
* function toggleSound(){
* if (sound1.isPlaying() && sound2.isPlaying()) {
* sound1.stop();
* sound2.stop();
* } else {
* sound1.play();
* sound2.play();
* }
* }
* </code></div>
*/
setInput(source, smoothing) {
p5sound.meter.disconnect();
if (smoothing) {
this._workletNode.parameters.get('smoothing').value = smoothing;
}
// connect to the master out of p5s instance if no snd is provided
if (source == null) {
console.log(
'Amplitude input source is not ready! Connecting to main output instead'
);
p5sound.meter.connect(this._workletNode);
}
// connect to the sound if it is available
else if (source) {
source.connect(this._workletNode);
this._workletNode.disconnect();
this._workletNode.connect(this.output);
}
// otherwise, connect to the master out of p5s instance (default)
else {
p5sound.meter.connect(this._workletNode);
}
}
connect(unit) {
if (unit) {
if (unit.hasOwnProperty('input')) {
this.output.connect(unit.input);
} else {
this.output.connect(unit);
}
} else {
this.output.connect(this.panner.connect(p5sound.input));
}
}
disconnect() {
if (this.output) {
this.output.disconnect();
}
}
/**
* Returns a single Amplitude reading at the moment it is called.
* For continuous readings, run in the draw loop.
*
* @method getLevel
* @for p5.Amplitude
* @param {Number} [channel] Optionally return only channel 0 (left) or 1 (right)
* @return {Number} Amplitude as a number between 0.0 and 1.0
* @example
* <div><code>
* function preload(){
* sound = loadSound('assets/beat.mp3');
* }
*
* function setup() {
* let cnv = createCanvas(100, 100);
* cnv.mouseClicked(toggleSound);
* amplitude = new p5.Amplitude();
* }
*
* function draw() {
* background(220, 150);
* textAlign(CENTER);
* text('tap to play', width/2, 20);
*
* let level = amplitude.getLevel();
* let size = map(level, 0, 1, 0, 200);
* ellipse(width/2, height/2, size, size);
* }
*
* function toggleSound(){
* if (sound.isPlaying()) {
* sound.stop();
* } else {
* sound.play();
* }
* }
* </code></div>
*/
getLevel(channel) {
if (typeof channel !== 'undefined') {
if (this.normalize) {
return this.stereoVolNorm[channel];
} else {
return this.stereoVol[channel];
}
} else if (this.normalize) {
return this.volNorm;
} else {
return this.volume;
}
}
/**
* Determines whether the results of Amplitude.process() will be
* Normalized. To normalize, Amplitude finds the difference the
* loudest reading it has processed and the maximum amplitude of
* 1.0. Amplitude adds this difference to all values to produce
* results that will reliably map between 0.0 and 1.0. However,
* if a louder moment occurs, the amount that Normalize adds to
* all the values will change. Accepts an optional boolean parameter
* (true or false). Normalizing is off by default.
*
* @method toggleNormalize
* @for p5.Amplitude
* @param {boolean} [boolean] set normalize to true (1) or false (0)
*/
toggleNormalize(bool) {
if (typeof bool === 'boolean') {
this.normalize = bool;
} else {
this.normalize = !this.normalize;
}
this._workletNode.port.postMessage({
name: 'toggleNormalize',
normalize: this.normalize,
});
}
/**
* Smooth Amplitude analysis by averaging with the last analysis
* frame. Off by default.
*
* @method smooth
* @for p5.Amplitude
* @param {Number} set smoothing from 0.0 <= 1
*/
smooth(s) {
if (s >= 0 && s < 1) {
this._workletNode.port.postMessage({ name: 'smoothing', smoothing: s });
} else {
console.log('Error: smoothing must be between 0 and 1');
}
}
dispose() {
// remove reference from soundArray
var index = p5sound.soundArray.indexOf(this);
p5sound.soundArray.splice(index, 1);
if (this.input) {
this.input.disconnect();
delete this.input;
}
if (this.output) {
this.output.disconnect();
delete this.output;
}
this._workletNode.disconnect();
delete this._workletNode;
}
} |
JavaScript | class MoovieFervieSprite {
constructor(animationLoader, x, y, size) {
this.animationLoader = animationLoader;
this.x = x - size / 2 - 10;
this.y = y - 20;
this.size = size;
this.animationFrame = 1;
}
static UNSCALED_IMAGE_WIDTH = 376;
static UNSCALED_IMAGE_HEIGHT = 332;
/**
* Preload all the images by processing the svgs with the colors then flattening to images
* @param p5
*/
preload(p5) {
this.animationLoader.getAnimationImageWithManualFrame(
p5,
AnimationId.Animation.MoovieFervie,
1,
this.size
);
this.animationLoader.getAnimationImageWithManualFrame(
p5,
AnimationId.Animation.MoovieFervie,
2,
this.size
);
}
/**
* Draw the fervie sprite on the screen based on the properties
* @param p5
*/
draw(p5) {
//24 frames per second, blinks every 5 seconds for ~1/4 second
let image = null;
if (this.animationFrame < 115) {
image =
this.animationLoader.getAnimationImageWithManualFrame(
p5,
AnimationId.Animation.MoovieFervie,
1,
this.size
);
} else {
console.log("blink!");
image =
this.animationLoader.getAnimationImageWithManualFrame(
p5,
AnimationId.Animation.MoovieFervie,
2,
this.size
);
}
p5.image(image, this.x, this.y);
}
/**
* Update the moovie fervie sprite properties for each subsequent frame,
* updating the relative frame number for tracking the blink loop
*/
update(p5, environment) {
this.animationFrame++;
if (this.animationFrame > 120) {
this.animationFrame = 1;
}
}
} |
JavaScript | class App extends Component {
render() {
const { classes } = this.props;
// OR
// const classes = this.props.classes;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
>
<MenuIcon />
</IconButton>
<Typography
variant="subtitle1"
color="inherit"
className={classes.grow}
>
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<img src={logo} className={classes.imgSize} alt="logo" />
</div>
);
}
} |
JavaScript | class GradientProvider extends Component {
// getContext;
// renderInner;
constructor(props) {
super(props);
this.getContext = memoize(this.getContext.bind(this));
this.renderInner = this.renderInner.bind(this);
console.log("PROVIDER");
}
render() {
console.log("fuck");
if (!this.props.children) return null;
return <PresetContext.Consumer>{this.renderInner}</PresetContext.Consumer>;
}
renderInner(outerPresets) {
const context = this.getContext(this.props.presets, outerPresets);
console.log("RENDERINNER");
return (
<PresetContext.Provider value={context}>
{this.props.children}
</PresetContext.Provider>
);
}
/**
* Get the presets from the props, supporting both (outerPresets) => {}
* as well as object notation
*/
getPresets(presets, outerPresets) {
// if (isFunction(presets)) {
// const mergedTheme = presets(outerPresets);
// if (
// process.env.NODE_ENV !== "production" &&
// (mergedTheme === null ||
// Array.isArray(mergedTheme) ||
// typeof mergedTheme !== "object")
// ) {
// throw new StyledError(7);
// }
// return mergedTheme;
// }
// if (presets === null || Array.isArray(presets) || typeof presets !== "object") {
// throw new StyledError(8);
// }
if (!outerPresets && !presets) {
return gradients;
}
console.log(outerPresets, presets);
return { ...outerPresets, ...presets };
}
getContext(presets, outerPresets) {
return this.getPresets(presets, outerPresets);
}
} |
JavaScript | class SignUp extends Component {
constructor() {
super();
this.state = {
errorsThatExist: [],
hasReedemableCode: false,
listenerRemoved: false
}
this.onSubmit = this.onSubmit.bind(this);
}
/**
* An event handler that prevents default action (page refresh),
* checks to see if all values are fit for submission.
* Submits and conditionally redirects to profile page or to PayPal website
* according to payment status.
*
* NOTE: Could be further refactored to reduce runtime. - Zane
*
* @param {object} event
* @returns {boolean} false
*/
onSubmit(event) {
const target = event.target || event.srcElement;
let submit = document.querySelector(".signup_form #submit");
// Use IE5-8 fallback if event object not present
if (!event) {
event = window.event;
}
console.log("onSubmit() called");
event.preventDefault();
let firstName = target.first_name.value;
let revisedFirstName = [];
let nickName = target.nick_name.value;
let revisedNickName = [];
let lastName = target.last_name.value;
let nameArray = [firstName, nickName, lastName];
//let chapterID = 1;
let revisedLastName = [];
let email = target.email.value;
const birthday = target.birthday.value;
const gender = target.gender.value;
let street = target.street.value;
const country = target.country.value;
const state = target.state.value;
const city = target.city.value;
let zip = target.zip.value.toString();
let addressArray = [street, zip];
const securityQuestion = target.security_question.value;
let securityAnswer = target.security_answer.value;
const password = target.password.value;
const confirmPassword = event.target.confirm_password.value;
//let redeemableCode = target.redeemable_code.value;
const payment = parseInt(target.payment.value.split("").filter(string => string !== "$").join(""));
// Check if birthday and current date match variables
const date = new Date();
const currentDate = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
const birthYear = parseInt(birthday[0] + birthday[1] + birthday[2] + birthday[3]);
const birthMonth = parseInt(birthday[5] + birthday[6]);
const birthDay = parseInt(birthday[8] + birthday[9]);
const checkYears = birthYear <= currentDate[0];
const checkMonths = birthMonth <= currentDate[1];
const checkDays = birthDay <= currentDate[2];
const checkDates = this.props.checkDates(checkYears, checkMonths, checkDays, birthYear, birthMonth, currentDate[0], currentDate[1]);
// Array of form input IDs
const formInputIds = ["firstName", "lastName", "email", "birthday", "gender", "streetId", "countryId", "stateId", "cityId", "zipId",
"securityQuestion", "securityAnswer", "password", "payment"];
// Create error array
let error = [];
for (let input = 0; input < 11; input++) {
error[input] = document.createElement('p');
}
// Change border color of all input and select tags back to normal
for (let id = 0; id < formInputIds.length; id++) {
this.props.changeBorderColor(formInputIds[id]);
}
// Clear error text if it currently exists on the DOM
let errorsThatExist = this.state.errorsThatExist;
for (let errorNo = 0; errorNo < errorsThatExist.length; errorNo++) {
if (errorsThatExist[errorNo]) {
const element = document.getElementsByClassName(`error_${errorNo}`)[0];
element.parentElement.removeChild(element);
errorsThatExist[errorNo] = false;
}
}
firstName = this.props.sanitizeInput(firstName);
nickName = this.props.sanitizeInput(nickName);
lastName = this.props.sanitizeInput(lastName);
// Check if first name, nick name and last name exist
if (firstName.length === 0 || lastName.length === 0) {
if (!errorsThatExist[0]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[0];
const inputFirstName = document.getElementById("firstName");
const inputLastName = document.getElementById("lastName");
error[0].innerText = '*Please enter both your first and last name.';
error[0].className = "error_0";
error[0].style.fontSize = '.9rem';
error[0].style.color = '#C31F01';
formField.appendChild(error[0]);
if (firstName.length === 0) {
inputFirstName.style.borderColor = '#C31F01';
}
if (lastName.length === 0) {
inputLastName.style.borderColor = '#C31F01';
}
errorsThatExist[0] = true;
}
}
// Capitalize the first letter of any names if haven't been done so by user
if (firstName.length > 0) {
firstName = this.props.reviseName(firstName, revisedFirstName, "firstName", true);
}
if (nickName.length > 0) {
nickName = this.props.reviseName(nickName, revisedNickName, "nickName", true);
}
if (lastName.length > 0) {
lastName = this.props.reviseName(lastName, revisedLastName, "lastName", true);
}
// Check for valid email input and if it's already in use
if (!(this.props.emailIsValid(email))) {
if (!errorsThatExist[1]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[1];
const input = document.getElementById("email");
error[1].innerText = '*Please enter a valid email address.';
error[1].className = "error_1";
error[1].style.fontSize = '.9rem';
error[1].style.color = '#C31F01';
formField.appendChild(error[1]);
input.style.borderColor = '#C31F01';
errorsThatExist[1] = true;
}
} else {
// Do a query search in database to check if email entered in is unique. If it isn't, change value of boolean
let emailAlreadyExists = false;
// Do query search here
if (emailAlreadyExists) {
if (!errorsThatExist[1]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[1];
const input = document.getElementById("email");
error[1].innerText = '*Email address already exists.';
error[1].className = "error_1";
error[1].style.fontSize = '.9rem';
error[1].style.color = '#C31F01';
formField.appendChild(error[1]);
input.style.borderColor = '#C31F01';
errorsThatExist[1] = true;
}
}
}
// Check for birthday input
if (birthday === "" || !checkDates) {
if (!errorsThatExist[2]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[2];
const input = document.getElementById("birthday");
error[2].innerText = '*Please select a birthday that is under the current date.';
error[2].className = "error_2";
error[2].style.fontSize = '.9rem';
error[2].style.color = '#C31F01';
formField.appendChild(error[2]);
input.style.borderColor = '#C31F01';
errorsThatExist[2] = true;
}
}
// Check for gender selection
if (gender === "Gender") {
if (!errorsThatExist[3]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[3];
const input = document.getElementById("gender");
error[3].innerText = '*Please select a gender.';
error[3].className = "error_3";
error[3].style.fontSize = '.9rem';
error[3].style.color = '#C31F01';
formField.appendChild(error[3]);
input.style.borderColor = '#C31F01';
errorsThatExist[3] = true;
}
}
street = this.props.sanitizeInput(street);
zip = this.props.sanitizeInput(zip);
const formField = document.getElementsByClassName("signup_fields")[4];
const inputStreet = document.getElementById("streetId");
const inputCountry = document.getElementById("countryId");
const inputState = document.getElementById("stateId");
const inputCity = document.getElementById("cityId");
const inputZip = document.getElementById("zipId");
// Check for address input
if (street === "" || country === "" || state === "" || city === "" || zip === "") {
if (!errorsThatExist[4]) {
// Render error text and change boolean
error[4].innerText = '*Please enter or select a value in all address-related fields.';
error[4].className = "error_4";
error[4].style.fontSize = '.9rem';
error[4].style.color = '#C31F01';
formField.appendChild(error[4]);
inputStreet.style.borderColor = '#C31F01';
inputCountry.style.borderColor = '#C31F01';
inputState.style.borderColor = '#C31F01';
inputCity.style.borderColor = '#C31F01';
inputZip.style.borderColor = '#C31F01';
errorsThatExist[4] = true;
}
} else if (street.length > 150) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[4];
const inputStreet = document.getElementById("streetId");
error[4].innerText = '*Please enter a value in the "street" field less than 150 characters.';
error[4].className = "error_4";
error[4].style.fontSize = '.9rem';
error[4].style.color = '#C31F01';
formField.appendChild(error[4]);
inputStreet.style.borderColor = '#C31F01';
inputCountry.style.borderColor = '#C31F01';
inputState.style.borderColor = '#C31F01';
inputCity.style.borderColor = '#C31F01';
inputZip.style.borderColor = '#C31F01';
errorsThatExist[4] = true;
}
// Check for security question selection
if (securityQuestion === "Choose a security question") {
if (!errorsThatExist[5]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[5];
const input = document.getElementById("securityQuestion");
error[5].innerText = '*Please select a security question.';
error[5].className = "error_5";
error[5].style.fontSize = '.9rem';
error[5].style.color = '#C31F01';
formField.appendChild(error[5]);
input.style.borderColor = '#C31F01';
errorsThatExist[5] = true;
}
}
securityAnswer = this.props.sanitizeInput(securityAnswer);
// Check for security answer input
if (securityAnswer === "" || securityAnswer.length > 150) {
if (!errorsThatExist[6]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[6];
const input = document.getElementById("securityAnswer");
error[6].innerText = '*Please enter a security answer less than 150 characters.';
error[6].className = "error_6";
error[6].style.fontSize = '.9rem';
error[6].style.color = '#C31F01';
formField.appendChild(error[6]);
input.style.borderColor = '#C31F01';
errorsThatExist[6] = true;
}
}
// NOTE: Password fields aren't being sanitized because they're being hashed/encoded. - Zane
// Check if password fields match
if (password !== confirmPassword || password === "" || password.length < 3 || password.length > 30) {
if (!errorsThatExist[7]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[7];
const inputPassword = document.getElementById("password");
const inputConfirmPassword = document.getElementById("confirmPassword");
if (password === "" || password.length < 3 || password.length > 30) {
error[7].innerText = '*Please enter a password between 3 and 30 characters.';
}
if (password !== confirmPassword) {
error[7].innerText = '*Your password inputs do not match.';
}
error[7].className = "error_7";
error[7].style.fontSize = '.9rem';
error[7].style.color = '#C31F01';
formField.appendChild(error[7]);
inputPassword.style.borderColor = '#C31F01';
inputConfirmPassword.style.borderColor = '#C31F01';
errorsThatExist[7] = true;
}
}
// Input sanitization for redeemableCode
// for (let inputIndex = 0; inputIndex < redeemableCode.length; inputIndex++) {
// if (redeemableCode[inputIndex] === "<") {
// redeemableCode = redeemableCode.replace(redeemableCode[inputIndex], "<");
// }
// if (redeemableCode[inputIndex] === ">") {
// redeemableCode = redeemableCode.replace(redeemableCode[inputIndex], ">");
// }
// if (redeemableCode[inputIndex] === "&") {
// redeemableCode = redeemableCode.replace(redeemableCode[inputIndex], "&");
// }
// }
// Check for valid redeemable code input offered in promotional email
// if (redeemableCode === "XGDV9DJZ") {
// this.setState({
// hasReedemableCode: true
// });
// }
// Check if pay field is greater than 0
// NOTE: If new user has redeemable code, they can bypass having to pay
if (payment === 0 && !this.state.hasReedemableCode) {
if (!errorsThatExist[8]) {
// Render error text and change boolean
const formField = document.getElementsByClassName("signup_fields")[8];
const input = document.getElementById("payment");
error[8].innerText = '*Please enter a value greater than 0.';
error[8].className = "error_8";
error[8].style.fontSize = '.9rem';
error[8].style.color = '#C31F01';
formField.appendChild(error[8]);
input.style.borderColor = '#C31F01';
errorsThatExist[8] = true;
}
}
// Check if any errors exists before sending data to API
for (let errorNo = 0; errorNo < errorsThatExist.length; errorNo++) {
if (errorsThatExist[errorNo]) {
return false;
}
}
// After-submit code
// Disable submit button
submit.disabled = true;
submit.setAttribute("class", "disabled_btn");
if (window.removeEventListener) { // If event listener supported
// Remove pop-up warning of unsaved data if user attempts to leave page
window.removeEventListener("beforeunload", this.props.displayUnloadMessage, false);
} else {
window.detachEvent("beforeunload", this.props.displayUnloadMessage);
}
this.setState({ listenerRemoved: true });
/* let addressID = 0; //not sure if variable needs to be declared here
let api_url = `http://localhost:8001/createAddress/${street}/${country}/${state}/${city}/${zip}/` ;
axios.post(api_url)
.then(res => {
console.log(res);
console.log(res.data);
console.log("ADDRESSID11: " + res.data.ID);
addressID = res.data.ID;
})
.catch(error => {
console.log("error");
if (error.response){
// When response status code is out of 2xx range
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if(error.request) {
// When no response was recieved after request was made
console.log(error.request)
} else {
console.log(error.message)
}
});
console.log("ADDRESSID: " + addressID);
api_url = `http://localhost:8001/createUser/${addressID}/${email}/${password}/${firstName}/${lastName}/${birthday}/${gender}/${securityQuestion}/${securityAnswer}` ;
axios.post(api_url)
//axios.post(api_url, {testChapter})
.then(res => {
console.log(res);
console.log(res.data);
})
.catch(error => {
console.log("error");
if (error.response){
// When response status code is out of 2xx range
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if(error.request) {
// When no response was recieved after request was made
console.log(error.request)
} else {
console.log(error.message)
}
}); */
}
componentDidMount() {
// When component is rendered, bring user to top of page
window.scrollTo(0, 0);
// This script tag is important htmlFor sign-up form to work properly.
// Provides country data htmlFor users to help insert exact address location.
// Src: https://geodata.solutions
if (!this.props.geoDataExists) {
const script = document.createElement("script");
script.src = "//geodata.solutions/includes/countrystatecity.js";
script.async = true;
script.className = "geodata_script";
document.body.appendChild(script);
this.props.setGeoDataExists();
}
if (window.addEventListener) { // If event listener supported
// Add pop-up warning of unsaved data if user attemps to leave page
window.addEventListener("beforeunload", this.props.displayUnloadMessage, false);
} else {
window.attachEvent("beforeunload", this.props.displayUnloadMessage, false);
}
this.setState({ listenerRemoved: false });
}
componentWillUnmount() {
if (!this.state.listenerRemoved) {
if (window.removeEventListener) { // If event listener supported
// Remove pop-up warning of unsaved data if user attempts to leave page
window.removeEventListener("beforeunload", this.props.displayUnloadMessage, false);
} else {
window.detachEvent("beforeunload", this.props.displayUnloadMessage);
}
}
// Remove geodata script from DOM
if (this.props.geoDataExists) {
const geoDataScript = document.getElementsByClassName('geodata_script')[0];
geoDataScript.parentElement.removeChild(geoDataScript);
this.props.setGeoDataExists();
}
}
render() {
return (
<React.Fragment>
<div className="adoption_agreement">
<div className="MsoNormal"><strong><span>Adoption Agreement</span></strong></div><br />
<p>New Haven Native American Church’s Constitution limits membership in the Native American Church to those who have been duly adopted by the President of the Church. This adoption is an ancient principle and Ceremony called "Making Relations." The Ceremony involves two parts: First, that you perform by you in your location; and second, which the President of the Church performs at this location.</p><br />
<p>The Native American Church allows individuals to exercise the freedom the Creator has given them to follow the dictates of religion according to how they feel directed by the Spirit. Members of the Native American Church must have sincere belief and a willingness to abide by the simple truths found in our Constitution and the Ethical Code of Conduct. The Church, however, does restrict membership to individuals at the age of accountability, that age being eight years old, and only to those who feel called by the Creator to become a Healer, which are also called Medicine Men and Medicine Women. All people can be healers and assist this world in becoming a better place. To be established as a Healer/Medicine Person, one must place themselves in one or more of the categories below.</p><br />
<ol>
<strong><li>As a Healer of people or animals. These are Medicine Men and Women of the Native American Church whose focus is in relieving the suffering of people or animals.</li></strong><br />
<strong><li>As a Healer of the family unit. These are Medicine Men and Women of the Native American Church who focus their ceremonial healing in family issues and in healing the values of family life.</li></strong><br />
<strong><li>As a Healer of the community. These are Medicine Men and Women of the Native American Church whose focus is more toward building up the Chapters, Communities, and so forth.</li></strong><br />
<strong><li>As a Healer of Society. These are Medicine Men and Women of the Native American Church that focus on repairing social systems or situations.</li></strong><br />
<strong><li>As a Healer of the Planet. These are Medicine Men and Women of the Native American Church whose focus is on restoring sustainable care of our Earth Mother and to educate others in the responsible use of her resources.</li></strong><br />
</ol><br />
<p>Membership in the New Haven Native American Church is permanent, meaning once an individual is a member of the Church Family, they can only be removed by their own personal request or by a serious infraction against the Church's Constitution or Ethical Code of Conduct. This practice of "Making Relations" or "Spiritual Adoption" is an ancient religious practice and should be taken seriously. This is the same principle that that Chief Joseph became Chief of the Nez Perce People, even though by today's accepted or legal standards, he could not be considered Nez Perce. Because of this ancient practice, Chief Joseph's signature was accepted as authoritative by the United States Federal Government in the Nez Perce Treaty.</p><br />
<p>The Native American Church has been recognized by the High Court as an "other organized group or community" of Indians and therefore all members of the Native American Church are legally defined as "Indians" even though they may not be enrolled members or recognized by any Tribe or Band. Also, the United Nations Declaration on the Rights of Indigenous Peoples states in Article 33 section one, "Indigenous peoples have the right to determine their own identity or membership in accordance with their customs and traditions."</p><br />
<p>There are many benefits, including legal ones, in becoming Spiritually Adopted, and any person of any ethnic background may request adoption if they have sincerity of belief. (Read more about the legal benefits under the "EDUCATION" tab above.) To be a "Member of Good Standing", one must be willing to make the following Declarations of Intention, as Covenant Obligations, which are described in the following:</p><br />
<h3>Declarations:</h3>
<ol>
<strong><li>It is my belief that Natural Medicine is a part of my established freedom to practice my Religion.</li></strong><br />
<strong><li>I will follow the practice of "First, Do Good" and I will, to the best of my ability, make this the guiding practice of my Healing Ministry.</li></strong><br />
<strong><li>For my development as a Healing Minister, I will faithfully study traditional healing methods and work to become educated in the various materials suggested by the President of the New Haven Native American Church. </li></strong><br />
<strong><li>I will donate from my surplus, as the Spirit directs, to the Church so that the Ministry of the Church may move forward and become fully established in all areas of the world. (The Church does not have a paid clergy so all donations go to building up the Church and giving greater support to its members.)</li></strong><br />
<strong><li>I will strive to establish a Native American Church Chapter in my area, if none is already present, and I will dedicate time, talent and resources, as suggested to me by the Spirit, to forward the purpose of that Chapter.</li></strong><br />
</ol><br />
<p>Covenant Obligations are the foundation of furthering the New Haven Native American Church's Ministry and Healing the World depends upon your faithfulness. If you feel that you can be true to the Declarations and can place yourself in at least one category above, then your request for Spiritual Adoption will be approved.</p><br />
</div>
<React.Fragment>
<form className="signup_form" onSubmit={this.onSubmit}>
<div className="top_div center_text">
<h2>Adoption form</h2>
<p>Pay what you'd like. Join our church today!</p>
</div>
<fieldset className="signup_fieldset">
<div className="signup_fields">
<label htmlFor="firstName">First Name</label><br />
<input className="signup_input" type="text" id="firstName" name="first_name" maxLength="50" placeholder="First Name" /><br />
<label htmlFor="nickName">Nick Name</label><br />
<input className="signup_input" type="text" id="nickName" name="nick_name" maxLength="50" placeholder="Nick Name" /><br />
<label htmlFor="lastName">Last Name</label><br />
<input className="signup_input" type="text" id="lastName" name="last_name" maxLength="50" placeholder="Last Name" /><br />
</div>
<div className="signup_fields">
<label htmlFor="email">Email</label><br />
<input className="signup_input" type="text" id="email" name="email" maxLength="320" placeholder="Email" /><br />
</div>
<div className="signup_fields">
<label htmlFor="birthday">Birthday</label><br />
<input className="signup_input" type="date" id="birthday" name="birthday" /><br />
</div>
<div className="signup_fields">
<label htmlFor="gender">Gender</label><br />
<select id="gender" name="gender">
<option>Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br />
</div>
<div className="signup_fields">
<label htmlFor="address">Physical Address</label><br />
<input className="signup_input" type="text" name="street" id="streetId" maxLength="150" placeholder="Building number, Street name, Apartment ID" />
<div className="geo_location">
<select name="country" className="countries" id="countryId">
<option value="">Select Country</option>
</select>
</div>
<div className="geo_location">
<select name="state" className="states" id="stateId">
<option value="">Select State</option>
</select>
</div>
<div className="geo_location">
<select name="city" className="cities" id="cityId">
<option value="">Select City</option>
</select>
</div><br />
<input type="text" name="zip" id="zipId" maxLength="10" placeholder="Zip" /><br />
</div>
<div className="signup_fields">
<label htmlFor="securityQuestion">Select your security question here</label><br />
<select id="securityQuestion" name="security_question">
<option>Choose a security question</option>
<option value="question_1">What is your favorite car?</option>
<option value="question_2">What city were you born in?</option>
<option value="question_3">What is your favorite color?</option>
</select><br />
</div>
<div className="signup_fields">
<label htmlFor="securityAnswer">Type your security answer here</label><br />
<input className="signup_input" type="text" id="securityAnswer" name="security_answer" maxLength="150" placeholder="Type your security answer here" /><br />
</div>
<div className="signup_fields">
<label htmlFor="password">Password</label><br />
<input className="signup_input" type="password" id="password" name="password" minLength="3" maxLength="30" placeholder="Password" /><br />
<label htmlFor="confirm_password">Confirm Password</label><br />
<input className="signup_input" type="password" id="confirmPassword" name="confirm_password" minLength="3" maxLength="30" placeholder="Confirm Password" /><br />
<input onClick={this.props.showPassword} type="checkbox" id="showPassword" name="show_password" />
<label htmlFor="showPassword">Show password</label><br />
</div>
{/* Code snippet for newsletter checkbox, which is currently an unavailable feature in the beta release. - Zane */}
{/*<div className="signup_fields">
<div className="newsletter_div center_text">
<input type="checkbox" id="newsletter" name="newsletter" />
<label className="center_text" htmlFor="newsletter">Check this box to sign up for our newsletter</label><br />
</div>
</div>*/}
{/* Insert e-signature widget here. */}
<div className="signup_fields">
<label htmlFor="redeemableCode">Redeemable Code</label><br />
<input className="signup_input" type="text" id="redeemableCode" name="redeemable_code" maxLength="8" placeholder="Redeemable Code" /><br />
</div>
<div className="signup_fields">
<label className="center_text" htmlFor="payment">Pay Us What You'd Like</label><br />
<input className="signup_input" type="string" id="payment" name="payment" placeholder="0" defaultValue="$0.00" /><br />
<div className="pay_buttons_div">
<button className="pay_button" type="button" value="1" onClick={() => { document.getElementById("payment").value = "$1.00" }}>$1</button>
<button className="pay_button" type="button" value="5" onClick={() => { document.getElementById("payment").value = "$5.00" }}>$5</button>
<button className="pay_button" type="button" value="10" onClick={() => { document.getElementById("payment").value = "$10.00" }}>$10</button>
<button className="pay_button" type="button" value="20" onClick={() => { document.getElementById("payment").value = "$20.00" }}>$20</button>
</div>
</div>
<div className="signup_fields">
<div className="pay_with_div center_text">
<button id="submit" className="paypal_btn" type="submit">Pay with PayPal</button>
{/* Code snippet for bitcoin payment option, which is currently an unavailable feature in the beta release. - Zane */}
{/*<p>Or</p>
<button id="submit" className="bitcoin_btn" type="submit">Pay with Bitcoin</button>*/}
</div>
</div>
<div className="signup_fields agreement_div">
<div className="newsletter_div center_text">
<input type="checkbox" id="agreement" name="agreement" />
<label className="center_text" htmlFor="agreement"> I agree to the <b>Adoption Agreement</b> and <Link to="/terms_of_service" target="_blank">Terms Of Service</Link>.</label><br />
</div>
</div>
</fieldset>
</form>
</React.Fragment>
</React.Fragment>
);
}
} |
JavaScript | class SliderSelect extends React.Component {
static propTypes = {
/** @type {Item[]} */
options: PropTypes.array, // List of the options (see the type Item)
// Callback exectued when the selected option changes
// If waitForChangeConfirmation is set to true, then the component
// waits for this callback to return either true or false to confirm
// if the choice can be made
// A promise can be returned for asynchronous confirmation
/** @type {(item: Item, path?: string[]) => (void|boolean|Promise<boolean>)} */
onValueChange: PropTypes.func,
/** @type {string} */
value: PropTypes.string, // Initial selected value (value of an Item)
className: PropTypes.string,
placeholder: PropTypes.string,
clearable: PropTypes.bool,
// Whether the user can select an intermediate node (not a leaf)
allowNonLeafSelection: PropTypes.bool,
// Whether the component should wait for the onValueChange callback to
// return true before confirming the user's choice; if false, then
// nothing would happen
waitForChangeConfirmation: PropTypes.bool,
};
static defaultProps = {
onValueChange: () => { },
clearable: true,
allowNonLeafSelection: true,
waitForChangeConfirmation: false,
};
constructor(props) {
super(props);
this.state = {
/** @type {Item} */
selectedItem: props.options
? props.options.find((item) => item.value === props.value)
: null,
closed: true,
fullList: props.options || [], // Original list of options
filteredOptions: props.options || [], // Filtered list of options
pathToCurrentItemsList: [], // List of all of the items leading to the current list
pathToSelectedItem: [], // Same as pathToCurrentItemsList but for the selected item
selectedIndex: 0, // Index of the selected option (via the keyboard)
waitingConfirmation: false, // Whether we're waiting a selection confirmation
};
// -------------------- BINDINGS -----------------------
this.onType = this.onType.bind(this);
this.onEnterSearch = this.onEnterSearch.bind(this);
this.onSliderPrev = this.onSliderPrev.bind(this);
this.onScreenClick = this.onScreenClick.bind(this);
this.onMouseDownOption = this.onMouseDownOption.bind(this);
this.toggle = this.toggle.bind(this);
this.open = this.open.bind(this);
this.close = this.close.bind(this);
this.selectItem = this.selectItem.bind(this);
this.clearSelectedItem = this.clearSelectedItem.bind(this);
// --------------------------------------------------------
}
UNSAFE_componentWillReceiveProps(newProps) {
// If we get the list of options asynchronously...
if (newProps.options.length && !this.state.fullList.length) {
this.setState({
fullList: newProps.options || [],
filteredOptions: newProps.options || [],
});
}
// If we get new options...
if (newProps.options !== this.props.options) {
const selectedIndex = (newProps.options && newProps.value)
? newProps.options.findIndex((item) => item.value === newProps.value)
: -1;
const selectedItem = selectedIndex !== -1
? newProps.options[selectedIndex]
: null;
this.setState({
fullList: newProps.options || [],
filteredOptions: newProps.options || [],
selectedItem,
selectedIndex: selectedIndex !== -1 ? selectedIndex : 0,
pathToCurrentItemsList: [],
pathToSelectedItem: [],
});
} else if (newProps.value !== this.props.value) {
// If the value of the select is changed via the props, we update
// the select item in the component
const selectedItem = this.props.options
&& this.props.options.find((item) => item.value === newProps.value);
if (selectedItem) {
this.setState({ selectedItem });
}
}
}
componentWillUnmount() {
// We remove the handler that is used to close the
// dropdown when the user clicks outside
window.removeEventListener('click', this.onScreenClick);
}
/**
* Event handler executed when the user types in the
* search input
* @param {KeyboardEvent} evt
*/
async onType(evt) {
switch (evt.keyCode) {
// key up
case 38: {
const index = this.state.selectedIndex > 0
? this.state.selectedIndex - 1
: this.state.filteredOptions.length - 1;
this.setSelectedIndex(index);
break;
}
// key down
case 40: {
const index = (this.state.selectedIndex < this.state.filteredOptions.length - 1)
? this.state.selectedIndex + 1
: 0;
this.setSelectedIndex(index);
break;
}
// enter key
case 13: {
if (this.state.selectedIndex !== -1 && this.state.filteredOptions.length) {
const selectedItem = this.state.filteredOptions[this.state.selectedIndex];
await this.selectItem(selectedItem);
}
break;
}
// esc key
case 27: {
this.close();
break;
}
// Typing text
default: {
const target = evt.currentTarget;
// We can't get the value of the input before
// the input gets updated
setTimeout(() => {
/** @type {string} */
const { value } = target;
const listTofilter = this.getItemsListAtCurrentLevel(this.state.pathToCurrentItemsList);
const filteredOptions = listTofilter
.filter((item) => item.label.toLowerCase().match(value.toLowerCase()));
this.setState({ filteredOptions });
}, 0);
break;
}
}
}
/**
* Event handler executed when the user places the
* focus on the search input
*/
onEnterSearch() {
if (this.state.closed) this.open();
}
/**
* Event handler executed when the user clicks on the right
* arrow of an options (meaning the options has sub-items)
* @param {MouseEvent} e Event object
* @param {Item} item Item that is clicked
*/
onSliderNext(e, item) {
e.stopPropagation();
const newPath = this.state.pathToCurrentItemsList.slice();
newPath.push(item);
const items = this.getItemsListAtCurrentLevel(newPath);
this.setState({
pathToCurrentItemsList: newPath,
filteredOptions: items,
});
}
/**
* Event handler executed when the user returns to a previous
* level
* @param {MouseEvent} e Event object
*/
onSliderPrev(e) {
e.stopPropagation();
const newPath = this.state.pathToCurrentItemsList.slice();
newPath.pop();
const items = this.getItemsListAtCurrentLevel(newPath);
this.setState({
pathToCurrentItemsList: newPath,
filteredOptions: items,
});
}
/**
* Event handler executed when the user clicks somewhere
* This handler is used to close the dropdown if the user
* clicks outside of it
* @param {MouseEvent} evt
*/
onScreenClick(evt) {
if (this.el.contains && !this.el.contains(evt.target)) {
this.close();
// We remove the now useless hander
window.removeEventListener('click', this.onScreenClick);
}
}
/**
* Event handler executed when the user clicks on
* an option
* @param {MouseEvent} e Event object
* @param {Item} item Associated item
*/
async onMouseDownOption(e, item) {
// If the element is not the option itself but
// the button to go a level deeper then we
// don't do anything
if (e.target instanceof HTMLButtonElement) return;
// If the user must select a leaf node, then if the
// option they clicked is not a leaf, we display
// the nested items of that item
if (!this.props.allowNonLeafSelection && item.items && item.items.length) {
this.onSliderNext(e, item);
return;
}
e.stopPropagation();
await this.selectItem(item);
}
/**
* Set the selected options (via keyboard)
* @param {number} index
*/
setSelectedIndex(index) {
this.setState({ selectedIndex: index });
}
/**
* Return the list of items that are located at the branch
* designated by the list of items passed as argument
* @param {Item[]} path List of items
* @returns {Item[]}
*/
getItemsListAtCurrentLevel(path) {
let list = this.state.fullList;
if (path.length) {
for (let i = 0; i < path.length; i++) {
const item = list.find((it) => it.value === path[i].value);
if (item.items) list = item.items;
else break;
}
}
return list;
}
/**
* Toggle the dropdown
* @param {MouseEvent} e
*/
toggle(e) {
if (e.target === this.input) return;
e.stopPropagation();
if (this.state.closed) this.open();
else this.close();
}
/**
* Expand the dropdown
*/
open() {
// This listener is used to close the dropdown
// when the user clicks outside of it
window.addEventListener('click', this.onScreenClick);
this.setState({ closed: false }, () => {
if (this.input) this.input.focus();
});
}
/**
* Close the dropdown
*/
close() {
// We remove the handler that is used to close the
// dropdown when the user clicks outside
window.removeEventListener('click', this.onScreenClick);
// We close the dropdown and reset the selected index
this.setState({ closed: true });
// If there's is no selected item, then we completely reset
// the state of the dropdown
if (!this.state.selectedItem) {
this.setState({
pathToCurrentItemsList: [],
pathToSelectedItem: [],
filteredOptions: this.state.fullList,
selectedIndex: 0,
});
} else {
// If there's a selected option then we restore the
// dropdown to the state where the option is
const filteredOptions = this.getItemsListAtCurrentLevel(this.state.pathToSelectedItem);
this.setState({
pathToCurrentItemsList: this.state.pathToSelectedItem,
filteredOptions,
selectedIndex: filteredOptions.findIndex((item) => item === this.state.selectedItem),
});
}
if (this.input) {
this.input.value = '';
}
}
/**
* Set the selected item
* NOTE: this is an asynchronous method
* @param {Item} item
*/
async selectItem(item) {
const path = this.state.pathToCurrentItemsList;
// We wait for the confirmation to select this option
return new Promise(async (resolve, reject) => {
this.setState({ waitingConfirmation: true });
const res = await this.props.onValueChange(item, path.map((it) => it.value), 'vocabulary');
this.setState({ waitingConfirmation: false });
if (!this.props.waitForChangeConfirmation || !!res) resolve();
else reject();
})
// If we've the confirmation the user can select this option, then we set it
.then(() => {
this.setState({
selectedItem: item,
pathToSelectedItem: path,
}, () => this.close());
})
// If that's denied, we don't care, we just don't do anything
.catch(() => {});
}
/**
* Reset the selected item
* @param {MouseEvent} e
*/
clearSelectedItem(e) {
e.stopPropagation();
this.setState({
selectedItem: null,
pathToCurrentItemsList: [],
pathToSelectedItem: [],
filteredOptions: this.state.fullList,
selectedIndex: 0,
});
this.props.onValueChange();
}
render() {
const {
className, options, placeholder, clearable,
} = this.props;
const {
closed,
filteredOptions,
selectedItem,
pathToCurrentItemsList,
selectedIndex,
waitingConfirmation,
} = this.state;
const cNames = classnames({
'c-custom-select -search': true,
'-closed': closed,
}, className);
const noResults = !!(options.length && !filteredOptions.length);
let selectText = placeholder;
if (waitingConfirmation) {
selectText = (
<span>
<Spinner isLoading className="-light -small -inline" />
{' '}
Waiting for action
</span>
);
} else if (selectedItem) selectText = selectedItem.as || selectedItem.label;
return (
<div ref={(node) => { this.el = node; }} className={cNames}>
<div
className="custom-select-text"
>
<input
aria-label={placeholder}
ref={(node) => { this.input = node; }}
className="custom-select-search"
type="search"
onFocus={this.onEnterSearch}
onKeyDown={this.onType}
/>
<div>
{selectText}
{/*! selectedItem && closed &&
<button className="icon-btn" onClick={this.toggle}>
<Icon name="icon-arrow-down" className="-small icon-arrow-down" />
</button>
*/}
{ selectedItem && clearable
&& (
<button className="icon-btn clear-button" onClick={this.clearSelectedItem}>
<Icon name="icon-cross" className="-smaller icon-cross" />
</button>
)}
</div>
</div>
{noResults
&& <span className="no-results">No results</span>}
{this.state.closed
|| (
<ul className="custom-select-options" role="listbox" aria-label={placeholder} ref={(node) => { this.options = node; }}>
{pathToCurrentItemsList.length > 0
&& (
<li
role="option"
aria-selected="false"
aria-label="Go back to the parent options"
className="title"
onClick={this.onSliderPrev}
>
<div>
<Icon name="icon-arrow-left-2" className="-small icon-arrow-left-2" />
<span>{pathToCurrentItemsList[pathToCurrentItemsList.length - 1].label}</span>
</div>
</li>
)}
{filteredOptions.map((item, index) => (
<li
role="option"
aria-selected={item === selectedItem}
className={classnames({ '-selected': index === selectedIndex })}
key={item.id || item.value}
onMouseEnter={() => { this.setSelectedIndex(index); }}
onMouseDown={(e) => this.onMouseDownOption(e, item)}
>
<span className="label">{item.label}</span>
{item.items && item.items.length
&& (
<button className="next" onClick={(e) => this.onSliderNext(e, item)}>
<Icon name="icon-arrow-right-2" className="-small icon-arrow-right-2" />
</button>
)}
</li>
))}
</ul>
)}
</div>
);
}
} |
JavaScript | class MemoryCacher extends BaseCacher {
/**
* Creates an instance of MemoryCacher.
*
* @param {object} opts
*
* @memberof MemoryCacher
*/
constructor(opts) {
super(opts);
// Cache container
this.cache = new Map();
// Start TTL timer
this.timer = setInterval(() => {
/* istanbul ignore next */
this.checkTTL();
}, 30 * 1000);
this.timer.unref();
}
/**
* Initialize cacher
*
* @param {any} broker
*
* @memberof Cacher
*/
init(broker) {
super.init(broker);
broker.localBus.on("$transporter.connected", () => {
// Clear all entries after transporter connected. Maybe we missed some "cache.clear" events.
this.clean();
});
}
/**
* Get data from cache by key
*
* @param {any} key
* @returns {Promise}
*
* @memberof MemoryCacher
*/
get(key) {
this.logger.debug(`GET ${key}`);
if (this.cache.has(key)) {
this.logger.debug(`FOUND ${key}`);
let item = this.cache.get(key);
if (this.opts.ttl) {
// Update expire time (hold in the cache if we are using it)
item.expire = Date.now() + this.opts.ttl * 1000;
}
return Promise.resolve(item.data);
}
return Promise.resolve(null);
}
/**
* Save data to cache by key
*
* @param {String} key
* @param {any} data JSON object
* @param {Number} ttl Optional Time-to-Live
* @returns {Promise}
*
* @memberof MemoryCacher
*/
set(key, data, ttl) {
if (ttl == null)
ttl = this.opts.ttl;
this.cache.set(key, {
data,
expire: ttl ? Date.now() + ttl * 1000 : null
});
this.logger.debug(`SET ${key}`);
return Promise.resolve(data);
}
/**
* Delete a key from cache
*
* @param {any} key
* @returns {Promise}
*
* @memberof MemoryCacher
*/
del(key) {
this.cache.delete(key);
this.logger.debug(`REMOVE ${key}`);
return Promise.resolve();
}
/**
* Clean cache. Remove every key by match
* @param {any} match string. Default is "**"
* @returns {Promise}
*
* @memberof Cacher
*/
clean(match = "**") {
this.logger.debug(`CLEAN ${match}`);
this.cache.forEach((value, key) => {
if (utils.match(key, match)) {
this.logger.debug(`REMOVE ${key}`);
this.cache.delete(key);
}
});
return Promise.resolve();
}
/**
* Check & remove the expired cache items
*
* @memberof MemoryCacher
*/
checkTTL() {
let now = Date.now();
this.cache.forEach((value, key) => {
let item = this.cache.get(key);
if (item.expire && item.expire < now) {
this.logger.debug(`EXPIRED ${key}`);
this.cache.delete(key);
}
});
}
} |
JavaScript | class Time extends React.Component {
constructor(props) {
super(props);
this.state = {
hours: Math.floor(props.value / 60),
minutes: props.value % 60,
};
this.handleChange = this.handleChange.bind(this);
this.getMinutesValue = this.getMinutesValue.bind(this);
}
// get the minutes value based on hours
getMinutesValue() {
const { hours, minutes } = this.state;
return parseInt(hours, 10) * 60 + parseInt(minutes, 10);
}
// depening on the input element changed set the state
handleChange(event) {
const { target } = event;
const { name, value } = target;
this.setState(
{
[name]: parseInt(value, 10),
},
() => {
this.props.onChange({
target: {
type: 'time',
name: this.props.name,
value: this.getMinutesValue(),
},
});
},
);
}
render() {
const { id, name, type, value, colon, maxHours, maxMinutes } = this.props;
const [hours = 0, minutes = 0] = getHoursMinsValue(
value,
maxHours,
maxMinutes,
);
const className = classNames({
[`time-${type}`]: true,
input: true,
});
const selector = id || name;
return (
<div className={className}>
<div className="time-input" id={selector}>
<input
type="number"
name="hours"
id={`${selector}-hours`}
min="0"
max={maxHours}
step="1"
value={`${hours}`}
onChange={this.handleChange}
/>
<span>{colon}</span>
<input
type="number"
id={`${selector}-minutes`}
name="minutes"
min="0"
max={maxMinutes}
step="1"
value={`${minutes}`}
onChange={this.handleChange}
/>
</div>
</div>
);
}
} |
JavaScript | class MyService {
// Retrieves a list of all resources from the service.
// Provider parameters will be passed as params.query.
async find(params) {
return [];
}
// Retrieves a single resource with the given id from the service.
async get(id, params) {}
// Creates a new resource with data.
// The method should return the newly created data. data may also be an array.
async create(data, params) {}
// Replaces the resource identified by id with data.
// The method should return the complete, updated resource data.
// id can also be null when updating multiple records, with params.query containing the query criteria.
async update(id, data, params) {}
// Merges the existing data of the resource identified by id with the new data.
// id can also be null indicating that multiple resources should be patched with params.query containing the query criteria.
async patch(id, data, params) {}
// Removes the resource with id.
// The method should return the removed resource.
// id can also be null, which indicates the deletion of multiple resources, with params.query containing the query criteria.
async remove(id, params) {}
// A special method that initializes the service, passing an instance of the Feathers application
// and the path it has been registered on.
// For services registered before app.listen is invoked, the setup function of each registered service
// is called on invoking app.listen. For services registered after app.listen is invoked, setup is
// called automatically by Feathers when a service is registered.
setup(app, path) {}
} |
JavaScript | class AbstractBackend {
constructor() {
this.silenceCallback = null;
}
/**
* Connect to the given destination. Destination should be an AudioNode.
*
* @param { AudioNode } destination The AudioNode to which audio is propagated
*/
/* eslint-disable-next-line */
connect(destination) {
throw "connect() must be implemented";
}
/** Disconnect from the currently-connected destination. */
disconnect() {
throw "disconnect() must be implemented";
}
/**
* Set the callback for when audio enters/exits silence
*
* @param { Function } cb Callback function with signature cb(silent)
*/
setSilenceCallback(cb) {
this.silenceCallback = cb;
}
} |
JavaScript | class RestHandler extends RequestHandler {
constructor(method, mask, resolver) {
super({
info: {
header: `${method} ${mask}`,
mask,
method,
},
ctx: restContext,
resolver,
});
this.checkRedundantQueryParameters();
}
checkRedundantQueryParameters() {
const { method, mask } = this.info;
const resolvedMask = getUrlByMask(mask);
if (resolvedMask instanceof URL && resolvedMask.search !== '') {
const queryParams = [];
resolvedMask.searchParams.forEach((_, paramName) => {
queryParams.push(paramName);
});
console.warn(`\
[MSW] Found a redundant usage of query parameters in the request handler URL for "${method} ${mask}". Please match against a path instead, and access query parameters in the response resolver function:
rest.${method.toLowerCase()}("${resolvedMask.pathname}", (req, res, ctx) => {
const query = req.url.searchParams
${queryParams
.map((paramName) => `\
const ${paramName} = query.get("${paramName}")`)
.join('\n')}
})\
`);
}
}
parse(request) {
return matchRequestUrl(request.url, this.info.mask);
}
getPublicRequest(request, parsedResult) {
return Object.assign(Object.assign({}, request), { params: parsedResult.params || {} });
}
predicate(request, parsedResult) {
return (isStringEqual(this.info.method, request.method) && parsedResult.matches);
}
log(request, response) {
const publicUrl = getPublicUrlFromRequest(request);
const loggedRequest = prepareRequest(request);
const loggedResponse = prepareResponse(response);
console.groupCollapsed('[MSW] %s %s %s (%c%s%c)', getTimestamp(), request.method, publicUrl, `color:${getStatusCodeColor(response.status)}`, response.status, 'color:inherit');
console.log('Request', loggedRequest);
console.log('Handler:', {
mask: this.info.mask,
resolver: this.resolver,
});
console.log('Response', loggedResponse);
console.groupEnd();
}
} |
JavaScript | class AuthData {
constructor(address, secrets, contacts){
if(!address) throw new Error('No address provided.');
if(!Array.isArray(secrets)) throw new Error('Secrets is not array.');
if(!Array.isArray(contacts)) throw new Error('Contacts is not array.');
this._address = address;
this._secrets = secrets || [];
this._contacts = contacts || [];
}
static get SESSION_KEY() { return 'authdata'; }
// create(...opts:any[]) => Promise<AuthData> -- create in persistent storage and return Promise of instance.
static create(opts) {
throw new Error('Implement .create()');
}
// restore() => AuthData -- restore from sessionStorage and return instance.
static restore() {
throw new Error('Implement .restore()');
}
// load(...opts:any[]) => Promise<AuthData> -- load from long-term storage (e.g. filesystem) and return Promise of instance.
static load(opts) {
throw new Error('Implement .load()');
}
// store() => AuthData -- store in sessionStorage and return current instance.
store() {
throw new Error('Implement .store()');
}
// save() => Promise<AuthData> -- save to long-term storage (e.g. filesystem) and return Promise with current instance.
save() {
throw new Error('Implement .save()');
}
// string -- address of the account.
get address() {
return this._address;
}
// Array<string> -- array of secrets.
get secrets() {
return this._secrets.slice();
}
// Array<Contact> -- array of Contacts.
get contacts() {
return this._contacts.slice();
}
//
// Magical methods to opererate on contacts. I don't want to break old wallet files and left as is. TODO: simplify or explain.
//
_applyUpdate(op, path, params, callback) {
// Exchange from numeric op code to string
if ("number" === typeof op) op = BLOB_OPS_REVERSE[op];
if ("string" !== typeof op) throw new Error("Blob update op code must be a number or a valid op id string");
// Separate each step in the "pointer"
const pointer = path.split("/");
const first = pointer.shift();
if (first !== "") {
throw new Error("Invalid JSON pointer: "+path);
}
this._traverse(this, pointer, path, op, params); // it was `this.data` instead of `this`.
this.save().then((data)=>{
console.log('Blob saved');
if (typeof callback === 'function') callback(null, data);
}).catch((err)=>{
console.error('Blob save failed!', err);
if (typeof callback === 'function') callback(err);
});
}
_traverse(context, pointer, originalPointer, op, params) {
let part = unescapeToken(pointer.shift());
if (Array.isArray(context)) {
if (part === '-') {
part = context.length;
} else if (part % 1 !== 0 || part < 0) {
throw new Error("Invalid pointer, array element segments must be " +
"a positive integer, zero or '-'");
}
} else if ("object" !== typeof context) {
return null;
} else if (!context.hasOwnProperty(part)) {
// Some opcodes create the path as they're going along
if (op === "set") {
context[part] = {};
} else if (op === "unshift") {
// this is not last element in path, and next is not array pointer
// so create object, not array
if (pointer.length !== 0 && pointer[0] !== '-' &&
(pointer[0] % 1 !== 0 || pointer[0] < 0)) {
context[part] = {};
} else {
context[part] = [];
}
} else {
return null;
}
}
if (pointer.length !== 0) {
return this._traverse(context[part], pointer, originalPointer, op, params);
}
switch (op) {
case "set":
context[part] = params[0];
break;
case "unset":
if (Array.isArray(context)) {
context.splice(part, 1);
} else {
delete context[part];
}
break;
case "extend":
if ("object" !== typeof context[part]) {
throw new Error("Tried to extend a non-object");
}
extend(context[part], params[0]);
break;
case "unshift": {
if ("undefined" === typeof context[part]) {
context[part] = [];
} else if (!Array.isArray(context[part])) {
throw new Error("Operator 'unshift' must be applied to an array.");
}
context[part].unshift(params[0]);
break;
}
case "filter": {
if (!Array.isArray(context[part])) break;
for (const [i, element] of context[part].entries()) {
if ("object" === typeof element
&& element.hasOwnProperty(params[0])
&& element[params[0]] === params[1]
) {
const subpointer = originalPointer+"/"+i;
const subcommands = normalizeSubcommands(params.slice(2));
subcommands.forEach((subcommand) => {
const op = subcommand[0];
const pointer = subpointer+subcommand[1];
this._applyUpdate(op, pointer, subcommand.slice(2));
});
}
}
break;
}
default: {
throw new Error("Unsupported op "+op);
}
}
}
/**
* Prepend an entry to an array.
*
* This method adds an entry to the beginning of an array.
*/
unshift(pointer, value, callback) {
this._applyUpdate('unshift', pointer, [value], callback);
}
/**
* Filter the row(s) from an array.
*
* This method will find any entries from the array stored under `pointer` and
* apply the `subcommands` to each of them.
*
* The subcommands can be any commands with the pointer parameter left out.
*/
filter(pointer, field, value, subcommands, callback) {
let params = Array.prototype.slice.apply(arguments);
if ("function" === typeof params[params.length-1]) callback = params.pop();
params.shift();
// Normalize subcommands to minimize the patch size
params = params.slice(0, 2).concat(normalizeSubcommands(params.slice(2), true));
this._applyUpdate('filter', pointer, params, callback);
}
} |
JavaScript | class SettingStandard extends Setting {
constructor(defaultValue, type, group, label, desc, toggle) {
super(defaultValue, type, group);
this.label = label;
this.desc = desc;
this.toggle = toggle;
}
} |
JavaScript | class ThreadChannel extends Channel {
/**
* @param {Guild} guild The guild the thread channel is part of
* @param {APIChannel} data The data for the thread channel
* @param {Client} [client] A safety parameter for the client that instantiated this
*/
constructor(guild, data, client) {
super(guild?.client ?? client, data, false);
/**
* The guild the thread is in
* @type {Guild}
*/
this.guild = guild;
/**
* The id of the guild the channel is in
* @type {Snowflake}
*/
this.guildId = guild?.id ?? data.guild_id;
/**
* A manager of the messages sent to this thread
* @type {MessageManager}
*/
this.messages = new MessageManager(this);
/**
* A manager of the members that are part of this thread
* @type {ThreadMemberManager}
*/
this.members = new ThreadMemberManager(this);
this._typing = new Map();
if (data) this._patch(data);
}
_patch(data) {
super._patch(data);
/**
* The name of the thread
* @type {string}
*/
this.name = data.name;
if ('guild_id' in data) {
this.guildId = data.guild_id;
}
if ('parent_id' in data) {
/**
* The id of the parent channel of this thread
* @type {Snowflake}
*/
this.parentId = data.parent_id;
}
if ('thread_metadata' in data) {
/**
* Whether the thread is locked
* @type {boolean}
*/
this.locked = data.thread_metadata.locked ?? false;
/**
* Whether the thread is archived
* @type {boolean}
*/
this.archived = data.thread_metadata.archived;
/**
* The amount of time (in minutes) after which the thread will automatically archive in case of no recent activity
* @type {number}
*/
this.autoArchiveDuration = data.thread_metadata.auto_archive_duration;
/**
* The timestamp when the thread's archive status was last changed
* <info>If the thread was never archived or unarchived, this is the timestamp at which the thread was
* created</info>
* @type {number}
*/
this.archiveTimestamp = new Date(data.thread_metadata.archive_timestamp).getTime();
}
if ('owner_id' in data) {
/**
* The id of the member who created this thread
* @type {?Snowflake}
*/
this.ownerId = data.owner_id;
}
if ('last_message_id' in data) {
/**
* The last message id sent in this thread, if one was sent
* @type {?Snowflake}
*/
this.lastMessageId = data.last_message_id;
}
if ('last_pin_timestamp' in data) {
/**
* The timestamp when the last pinned message was pinned, if there was one
* @type {?number}
*/
this.lastPinTimestamp = data.last_pin_timestamp ? new Date(data.last_pin_timestamp).getTime() : null;
}
if ('rate_limit_per_user' in data) {
/**
* The ratelimit per user for this thread (in seconds)
* @type {number}
*/
this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
}
if ('message_count' in data) {
/**
* The approximate count of messages in this thread
* <info>This stops counting at 50. If you need an approximate value higher than that, use
* `ThreadChannel#messages.cache.size`</info>
* @type {number}
*/
this.messageCount = data.message_count;
}
if ('member_count' in data) {
/**
* The approximate count of users in this thread
* <info>This stops counting at 50. If you need an approximate value higher than that, use
* `ThreadChannel#members.cache.size`</info>
* @type {number}
*/
this.memberCount = data.member_count;
}
if (data.member && this.client.user) this.members._add({ user_id: this.client.user.id, ...data.member });
if (data.messages) for (const message of data.messages) this.messages.add(message);
}
/**
* A collection of associated guild member objects of this thread's members
* @type {Collection<Snowflake, GuildMember>}
* @readonly
*/
get guildMembers() {
return this.members.cache.mapValues(member => member.guildMember);
}
/**
* The time at which this thread's archive status was last changed
* <info>If the thread was never archived or unarchived, this is the time at which the thread was created</info>
* @type {Date}
* @readonly
*/
get archivedAt() {
return new Date(this.archiveTimestamp);
}
/**
* The parent channel of this thread
* @type {?(NewsChannel|TextChannel)}
* @readonly
*/
get parent() {
return this.guild.channels.resolve(this.parentId);
}
/**
* Makes the client user join the thread.
* @returns {Promise<ThreadChannel>}
*/
join() {
return this.members.add('@me').then(() => this);
}
/**
* Makes the client user leave the thread.
* @returns {Promise<ThreadChannel>}
*/
leave() {
return this.members.remove('@me').then(() => this);
}
/**
* Gets the overall set of permissions for a member or role in this thread's parent channel, taking overwrites into
* account.
* @param {GuildMemberResolvable|RoleResolvable} memberOrRole The member or role to obtain the overall permissions for
* @returns {?Readonly<Permissions>}
*/
permissionsFor(memberOrRole) {
return this.parent?.permissionsFor(memberOrRole) ?? null;
}
/**
* The options used to edit a thread channel
* @typedef {Object} ThreadEditData
* @property {string} [name] The new name for the thread
* @property {boolean} [archived] Whether the thread is archived
* @property {ThreadAutoArchiveDuration} [autoArchiveDuration] The amount of time (in minutes) after which the thread
* should automatically archive in case of no recent activity
* @property {number} [rateLimitPerUser] The ratelimit per user for the thread in seconds
* @property {boolean} [locked] Whether the thread is locked
*/
/**
* Edits this thread.
* @param {ThreadEditData} data The new data for this thread
* @param {string} [reason] Reason for editing this thread
* @returns {Promise<ThreadChannel>}
* @example
* // Edit a thread
* thread.edit({ name: 'new-thread' })
* .then(editedThread => console.log(editedThread))
* .catch(console.error);
*/
async edit(data, reason) {
const newData = await this.client.api.channels(this.id).patch({
data: {
name: (data.name ?? this.name).trim(),
archived: data.archived,
auto_archive_duration: data.autoArchiveDuration,
rate_limit_per_user: data.rateLimitPerUser,
locked: data.locked,
},
reason,
});
return this.client.actions.ChannelUpdate.handle(newData).updated;
}
/**
* Sets whether the thread is archived.
* @param {boolean} [archived=true] Whether the thread is archived
* @param {string} [reason] Reason for archiving or unarchiving
* @returns {Promise<ThreadChannel>}
* @example
* // Archive the thread
* thread.setArchived(true)
* .then(newThread => console.log(`Thread is now ${newThread.archived ? 'archived' : 'active'}`))
* .catch(console.error);
*/
setArchived(archived = true, reason) {
return this.edit({ archived }, reason);
}
/**
* Sets the duration after which the thread will automatically archive in case of no recent activity.
* @param {ThreadAutoArchiveDuration} autoArchiveDuration The amount of time (in minutes) after which the thread
* should automatically archive in case of no recent activity
* @param {string} [reason] Reason for changing the auto archive duration
* @returns {Promise<ThreadChannel>}
* @example
* // Set the thread's auto archive time to 1 hour
* thread.setAutoArchiveDuration(60)
* .then(newThread => {
* console.log(`Thread will now archive after ${newThread.autoArchiveDuration} minutes of inactivity`);
* });
* .catch(console.error);
*/
setAutoArchiveDuration(autoArchiveDuration, reason) {
return this.edit({ autoArchiveDuration }, reason);
}
/**
* Sets whether the thread can be **unarchived** by anyone with `SEND_MESSAGES` permission.
* When a thread is locked only members with `MANAGE_THREADS` can unarchive it.
* @param {boolean} [locked=true] Whether the thread is locked
* @param {string} [reason] Reason for locking or unlocking the thread
* @returns {Promise<ThreadChannel>}
* @example
* // Set the thread to locked
* thread.setLocked(true)
* .then(newThread => console.log(`Thread is now ${newThread.locked ? 'locked' : 'unlocked'}`))
* .catch(console.error);
*/
setLocked(locked = true, reason) {
return this.edit({ locked }, reason);
}
/**
* Sets a new name for this thread.
* @param {string} name The new name for the thread
* @param {string} [reason] Reason for changing the thread's name
* @returns {Promise<ThreadChannel>}
* @example
* // Change the thread's name
* thread.setName('not_general')
* .then(newThread => console.log(`Thread's new name is ${newThread.name}`))
* .catch(console.error);
*/
setName(name, reason) {
return this.edit({ name }, reason);
}
/**
* Sets the rate limit per user for this thread.
* @param {number} rateLimitPerUser The new ratelimit in seconds
* @param {string} [reason] Reason for changing the thread's ratelimits
* @returns {Promise<ThreadChannel>}
*/
setRateLimitPerUser(rateLimitPerUser, reason) {
return this.edit({ rateLimitPerUser }, reason);
}
/**
* Whether the client user is a member of the thread.
* @type {boolean}
* @readonly
*/
get joined() {
return this.members.cache.has(this.client.user?.id);
}
/**
* Whether the thread is editable by the client user (name, archived, autoArchiveDuration)
* @type {boolean}
* @readonly
*/
get editable() {
return (this.ownerId === this.client.user.id && (this.type !== 'private_thread' || this.joined)) || this.manageable;
}
/**
* Whether the thread is joinable by the client user
* @type {boolean}
* @readonly
*/
get joinable() {
return (
!this.archived &&
!this.joined &&
this.permissionsFor(this.client.user)?.has(
this.type === 'private_thread' ? Permissions.FLAGS.MANAGE_THREADS : Permissions.FLAGS.VIEW_CHANNEL,
false,
)
);
}
/**
* Whether the thread is manageable by the client user, for deleting or editing rateLimitPerUser or locked.
* @type {boolean}
* @readonly
*/
get manageable() {
return this.permissionsFor(this.client.user)?.has(Permissions.FLAGS.MANAGE_THREADS, false);
}
/**
* Whether the client user can send messages in this thread
* @type {boolean}
* @readonly
*/
get sendable() {
return (
!this.archived &&
(this.type !== 'private_thread' || this.joined || this.manageable) &&
this.permissionsFor(this.client.user)?.any(
[
Permissions.FLAGS.SEND_MESSAGES,
this.type === 'private_thread' ? Permissions.FLAGS.USE_PRIVATE_THREADS : Permissions.FLAGS.USE_PUBLIC_THREADS,
],
false,
)
);
}
/**
* Whether the thread is unarchivable by the client user
* @type {boolean}
* @readonly
*/
get unarchivable() {
return this.archived && (this.locked ? this.manageable : this.sendable);
}
/**
* Deletes this thread.
* @param {string} [reason] Reason for deleting this thread
* @returns {Promise<ThreadChannel>}
* @example
* // Delete the thread
* thread.delete('cleaning out old threads')
* .then(deletedThread => console.log(deletedThread))
* .catch(console.error);
*/
delete(reason) {
return this.client.api
.channels(this.id)
.delete({ reason })
.then(() => this);
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel
/* eslint-disable no-empty-function */
get lastMessage() {}
get lastPinAt() {}
send() {}
startTyping() {}
stopTyping() {}
get typing() {}
get typingCount() {}
createMessageCollector() {}
awaitMessages() {}
createMessageComponentCollector() {}
awaitMessageComponent() {}
bulkDelete() {}
} |
JavaScript | class PirateChain extends Driver {
constructor(options) {
super({
timeout: 100, // 10 requests per second
supports: {
circulating: true,
blockchains: ['PirateChain'],
},
options,
});
}
/** total supply for native token
*
* @augments Driver.fetchTotalSupply
* @async
*/
async fetchTotalSupply() {
return Number(200000000);
}
/** circulating supply for native token
*
* @augments Driver.fetchCirculatingSupply
* @async
*/
async fetchCirculatingSupply() {
const { supply: circulating } = await this.request(
'https://explorer.pirate.black/api/marketcap',
);
return Number(circulating);
}
/**
* @augments Driver.getSupply
* @async
*/
async getSupply() {
const total = await this.fetchTotalSupply();
const circulating = await this.fetchCirculatingSupply();
return new Supply({
total,
circulating,
});
}
} |
JavaScript | class CreateBlueprintPage {
constructor() {
this.containerSelector = '[id="cmpsr-modal-crt-blueprint"]';
}
loading() {
// sometimes the style attribute is style="display: block; padding-right: 12px;"
browser.waitUntil(
() => browser.getAttribute(this.containerSelector, 'style').includes('display: block;'),
timeout,
'Cannot pop up Create Blueprint dialog'
);
}
get nameBox() {
const selector = '[id="textInput-modal-markup"]';
browser.waitUntil(
() => browser.hasFocus(selector),
timeout,
`Username input box in Create Blueprint dialog cannot get focused by selector ${selector}`
);
return $(selector);
}
get descriptionBox() {
const selector = '[id="textInput2-modal-markup"]';
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`Description input box in Create Blueprint dialog cannot be found by selector ${selector}`
);
return $(selector);
}
get createButton() {
const selector = 'span=Create';
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`Create button in Create Blueprint dialog cannot be found by selector ${selector}`
);
return $(selector);
}
get cancelButton() {
const selector = 'span=Cancel';
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`Cancel button in Create Blueprint dialog cannot be found by selector ${selector}`
);
return $(selector);
}
clickXButton() {
const selector = `${this.containerSelector} .close`;
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`X button in Create Blueprint dialog cannot be found by selector ${selector}`
);
// browser.click() does not work with Edge due to "Element is Obscured" error.
// https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5238133/
browser.execute((xButton) => {
document.querySelector(xButton).click();
return true;
}, selector);
}
get alert() {
const selector = `${this.containerSelector} .alert-danger strong`;
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`Required information is missing error message in Create Blueprint dialog cannot be found by selector ${selector}`
);
return $(selector);
}
get helpBlock() {
const selector = `${this.containerSelector} .help-block`;
browser.waitUntil(
() => browser.isVisible(selector),
timeout,
`A blueprint name is required error message in Create Blueprint dialog cannot be found by selector ${selector}`
);
return $(selector);
}
} |
JavaScript | class Roles extends Command {
constructor(bot) {
super(bot, 'settings.roleids', 'roleids', 'Get list of role ids');
this.allowDM = false;
this.requiresAuth = true;
}
/**
* Run the command
* @param {Message} message Message with a command to handle, reply to,
* or perform an action based on parameters.
* @returns {string} success status
*/
run(message) {
const roles = message.guild.roles.array().sort((a, b) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
}
return 0;
});
const longest = roles.map(role => role.name)
.reduce((a, b) => (a.length > b.length ? a : b));
const roleGroups = createGroupedArray(roles.map(role => `\`${rpad(role.name, longest.length, ' ')} ${role.id}\``), 17);
const metaGroups = createGroupedArray(roleGroups, 4);
metaGroups.forEach((metaGroup) => {
this.messageManager.embed(message, {
fields: metaGroup.map(roleGroup => ({
name: '_ _',
value: roleGroup.join('\n'),
})),
}, true, false);
});
return this.messageManager.statuses.SUCCESS;
}
} |
JavaScript | class favouritesController {
/**
* @description - Add a recipe as favourite
* @static
*
* @param {object} req - HTTP Request
* @param {object} res - HTTP Response
*
* @memberof favouritesController
*
* @returns {object} Class instance
*/
static addFavourite(req, res) {
return db.Recipe.findById(req.params.recipeId)
.then((foundRecipe) => {
if (!foundRecipe) {
return res.status(404)
.json({
status: 'fail',
message: 'recipe does not exist in catalogue'
});
}
return db.Favourite.findOne({
where: {
recipeId: req.params.recipeId,
userId: req.userId
}
})
.then((foundFavourite) => {
if (foundFavourite) {
return db.Favourite.destroy({
where: {
userId: req.userId,
recipeId: req.params.recipeId
}
})
.then(() => {
foundRecipe.decrement(
'favourite',
{ where: { id: req.params.recipeId } }
);
return res.status(200)
.json({
status: 'removed',
message: 'Recipe removed from favourite'
});
});
}
return db.Favourite.create({
userId: req.userId,
recipeId: req.params.recipeId
})
.then(() => {
foundRecipe.increment(
'favourite',
{ where: { id: req.params.recipeId } }
);
return res.status(200).json({
status: 'added',
message: 'recipe favourited',
addedFavourite: foundRecipe
});
});
})
.catch(() => res.status(500).json({
status: 'error',
message: 'Internal server error'
}));
});
}
/**
* @description Gets a user's favourites
*
* @param {object} req - HTTP Request
* @param {object} res - HTTP Response
*
* @memberof favouriteController
*
* @returns {object} Class instance
*/
static getAllFavourites(req, res) {
return db.Favourite.findAndCountAll({
where: {
userId: req.userId
}
}).then((all) => {
const limit = 6;
let offset = 0;
const page = parseInt((req.query.page || 1), 10);
const numberOfItems = all.count;
const pages = Math.ceil(numberOfItems / limit);
offset = limit * (page - 1);
db.Favourite.findAll({
where: {
userId: req.userId
},
limit,
offset,
order: [
['id', 'DESC']
],
include: [
{
model: db.Recipe,
attributes: ['name', 'ingredients', 'description', 'recipeImage']
}
]
})
.then(found => res.status(200)
.json({
status: 'success',
numberOfItems,
limit,
pages,
currentPage: page,
favourites: found
}))
.catch(() => res.status(500).json({
status: 'error',
message: 'Internal server error'
}));
});
}
} |
JavaScript | class SolidInsertFunctionHandler extends _ldflex.InsertFunctionHandler {
async createRangeExpressions(pathData, path, args) {
// Gather all values whose addition was requested
const values = await Promise.all(args.map(async rawValue => {
const value = await rawValue; // Strings indicate literals
if (typeof value === 'string') return (0, _dataModel.literal)(value); // Only literals and named nodes are supported
const termType = value && value.termType;
if (termType === 'literal' || termType === 'namedNode') return value;
throw new Error(`Unsupported argument: ${value}`);
}));
return [[{
subject: values
}]];
}
} |
JavaScript | class InlineResponse20076Data {
/**
* Constructs a new <code>InlineResponse20076Data</code>.
* EOD key figures.
* @alias module:model/InlineResponse20076Data
*/
constructor() {
InlineResponse20076Data.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>InlineResponse20076Data</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/InlineResponse20076Data} obj Optional instance to populate.
* @return {module:model/InlineResponse20076Data} The populated <code>InlineResponse20076Data</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse20076Data();
if (data.hasOwnProperty('referenceDate')) {
obj['referenceDate'] = ApiClient.convertToType(data['referenceDate'], 'Date');
}
if (data.hasOwnProperty('performance')) {
obj['performance'] = InlineResponse20072DataPerformance.constructFromObject(data['performance']);
}
if (data.hasOwnProperty('high')) {
obj['high'] = InlineResponse20072DataHigh.constructFromObject(data['high']);
}
if (data.hasOwnProperty('low')) {
obj['low'] = InlineResponse20072DataLow.constructFromObject(data['low']);
}
if (data.hasOwnProperty('volatility')) {
obj['volatility'] = ApiClient.convertToType(data['volatility'], 'Number');
}
}
return obj;
}
} |
JavaScript | class Type {
constructor (type) {
type.fields.forEach(field => {
if (field.name === undefined) {
throw new TypeError('Name prop is missed.')
}
if (field.type === undefined) {
throw new TypeError('Type prop is missed.')
}
})
this.fields = type.fields
}
size () {
return this.fields.reduce((accumulator, field) => {
if (fieldIsFixed(field)) {
return accumulator + field.type.size()
} else {
return accumulator + 8
}
}, 0)
}
/**
* Serialize data into array of 8-bit integers
* @param {Object} data
* @returns {Array}
*/
serialize (data) {
return serialization.serialize([], 0, data, this)
}
/**
* Get SHA256 hash
* @param {Object} data
* @returns {string}
*/
hash (data) {
return crypto.hash(data, this)
}
/**
* Get ED25519 signature
* @param {string} secretKey
* @param {Object} data
* @returns {string}
*/
sign (secretKey, data) {
return crypto.sign(secretKey, data, this)
}
/**
* Verifies ED25519 signature
* @param {string} signature
* @param {string} publicKey
* @param {Object} data
* @returns {boolean}
*/
verifySignature (signature, publicKey, data) {
return crypto.verifySignature(signature, publicKey, data, this)
}
} |
JavaScript | class ContentNegotiatorCommand extends Command {
/**
* Creates an instance of ContentNegotiatorCommand.
* @param {OdataRequest} request the current OData request
* @param {OdataResponse} response the current OData response
* @param {FormatManager} formatManager The current instance of format manager
* @param {ResponseContentNegotiator} contentNegotiator The current instance of ResponseContentNegotiator
* @param {LoggerFacade} logger the logger
*/
constructor (request, response, formatManager, contentNegotiator, logger) {
super()
this._request = request
this._response = response
this._formatManager = formatManager
this._negotiator = contentNegotiator
this._logger = logger
}
/**
* Executes the content negotiation. The content negotiation creates a `ResponseContract` object
* as a result with all necessary content negotiation information. The contract object is
* attached to the odata response instance.
*
* @param {Next} next The next callback to be called on finish
*/
execute (next) {
const contract = this._negotiator.negotiate(this._formatManager, this._request, this._request.getUriInfo())
if (contract.getContentTypeInfo()) {
this._logger.debug('Response contract content type:', contract.getContentTypeInfo().toString())
}
this._response.setContract(contract)
next()
}
/**
* Returns the current content negotiator instance.
* @returns {ContentNegotiator} the current instance of the negotiator
* @protected
*/
getNegotiator () {
return this._negotiator
}
/**
* Returns the current instance of the format manager.
* @returns {FormatManager} the current instance of the format manager
* @protected
*/
getFormatManager () {
return this._formatManager
}
} |
JavaScript | class Json extends Stringify {
/**
*
* @param {Object} options - Stream options
* @example <caption>Creates Json stream instance</caption>
* new Json()
*/
constructor(options) {
super(options);
}
/**
* @private
*/
_release() {
return JSON.parse(super._release());
}
} |
JavaScript | class Event {
/**
* Class constructor.
*/
constructor() {
this.cancelled = false;
this.defaultPrevented = false;
}
/**
* Cancel the event.
*/
cancel() {
this.cancelled = true;
}
/**
* Prevents the default action
*/
preventDefault() {
this.defaultPrevented = true;
}
} |
JavaScript | class ViewController extends AbstractElementController {
static getNorName () {
return "ViewController";
}
static getTemplate () {
return template;
}
} |
JavaScript | class LimitedCollection extends Collection {
constructor(options = {}, iterable) {
if (typeof options !== 'object' || options === null) {
throw new TypeError('INVALID_TYPE', 'options', 'object', true);
}
const { maxSize = Infinity, keepOverLimit = null, sweepInterval = 0, sweepFilter = null } = options;
if (typeof maxSize !== 'number') {
throw new TypeError('INVALID_TYPE', 'maxSize', 'number');
}
if (keepOverLimit !== null && typeof keepOverLimit !== 'function') {
throw new TypeError('INVALID_TYPE', 'keepOverLimit', 'function');
}
if (typeof sweepInterval !== 'number') {
throw new TypeError('INVALID_TYPE', 'sweepInterval', 'number');
}
if (sweepFilter !== null && typeof sweepFilter !== 'function') {
throw new TypeError('INVALID_TYPE', 'sweepFilter', 'function');
}
super(iterable);
/**
* The max size of the Collection.
* @type {number}
*/
this.maxSize = maxSize;
/**
* A function called to check if an entry should be kept when the Collection is at max size.
* @type {?Function}
*/
this.keepOverLimit = keepOverLimit;
/**
* A function called every sweep interval that returns a function passed to `sweep`.
* @type {?SweepFilter}
*/
this.sweepFilter = sweepFilter;
/**
* The id of the interval being used to sweep.
* @type {?Timeout}
*/
this.interval =
sweepInterval > 0 && sweepInterval !== Infinity && sweepFilter
? setInterval(() => {
const sweepFn = this.sweepFilter(this);
if (sweepFn === null)
return;
if (typeof sweepFn !== 'function')
throw new TypeError('SWEEP_FILTER_RETURN');
this.sweep(sweepFn);
}, sweepInterval * 1000)
: null;
}
set(key, value) {
var _a, _b;
if (this.maxSize === 0)
return this;
if (this.size >= this.maxSize && !this.has(key)) {
for (const [k, v] of this.entries()) {
const keep = (_b = (_a = this.keepOverLimit) === null || _a === void 0 ? void 0 : _a.call(this, v, k, this)) !== null && _b !== void 0 ? _b : false;
if (!keep) {
this.delete(k);
break;
}
}
}
return super.set(key, value);
}
/**
* Options for generating a filter function based on lifetime
* @typedef {Object} LifetimeFilterOptions
* @property {number} [lifetime=14400] How long, in seconds, an entry should stay in the collection
* before it is considered sweepable.
* @property {Function} [getComparisonTimestamp=e => e?.createdTimestamp] A function that takes an entry, key,
* and the collection and returns a timestamp to compare against in order to determine the lifetime of the entry.
* @property {Function} [excludeFromSweep=() => false] A function that takes an entry, key, and the collection
* and returns a boolean, `true` when the entry should not be checked for sweepability.
*/
/**
* Create a sweepFilter function that uses a lifetime to determine sweepability.
* @param {LifetimeFilterOptions} [options={}] The options used to generate the filter function
* @returns {SweepFilter}
*/
static filterByLifetime({ lifetime = 14400, getComparisonTimestamp = e => e === null || e === void 0 ? void 0 : e.createdTimestamp, excludeFromSweep = () => false, } = {}) {
if (typeof lifetime !== 'number') {
throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
}
if (typeof getComparisonTimestamp !== 'function') {
throw new TypeError('INVALID_TYPE', 'getComparisonTimestamp', 'function');
}
if (typeof excludeFromSweep !== 'function') {
throw new TypeError('INVALID_TYPE', 'excludeFromSweep', 'function');
}
return () => {
if (lifetime <= 0)
return null;
const lifetimeMs = lifetime * 1000;
const now = Date.now();
return (entry, key, coll) => {
if (excludeFromSweep(entry, key, coll)) {
return false;
}
const comparisonTimestamp = getComparisonTimestamp(entry, key, coll);
if (!comparisonTimestamp || typeof comparisonTimestamp !== 'number')
return false;
return now - comparisonTimestamp > lifetimeMs;
};
};
}
[_cleanupSymbol]() {
return this.interval ? () => clearInterval(this.interval) : null;
}
static get [Symbol.species]() {
return Collection;
}
} |
JavaScript | class SignIn extends React.Component {
onSubmit = (e) => {
e.preventDefault();
let password = this.refs.txtPassword.value,
email = this.refs.txtEmail.value;
let redirectToConvo = this.props.redirectToConvo;
this.props.signin({email, password});
}
render() {
const { props, onSubmit } = this;
return (
<div className="container">
<div className="row">
<form onSubmit={ onSubmit }>
<div className="col s6 offset-s3">
<div className="row valign-wrapper cont">
<div className="col s12">
<div className="card blue-grey darken-1 ">
<div className="card-content white-text">
<div className="row">
<div className="input-field col s12">
<input ref="txtEmail" id="icon_prefix" type="text" className="validate" />
<label htmlFor="icon_prefix">Email</label>
</div>
<div className="input-field col s12">
<input ref="txtPassword" id="icon_telephone" type="password" className="validate" />
<label htmlFor="icon_telephone">Password</label>
</div>
</div>
</div>
<div className="card-action">
<button className="btn waves-effect waves-light" type="submit" name="action">
Submit
</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
);
}
} |
JavaScript | class AttachmentService {
constructor(crowi) {
this.crowi = crowi;
}
async createAttachment(file, user, pageId = null) {
const { fileUploadService } = this.crowi;
// check limit
const res = await fileUploadService.checkLimit(file.size);
if (!res.isUploadable) {
throw new Error(res.errorMessage);
}
const Attachment = this.crowi.model('Attachment');
const fileStream = fs.createReadStream(file.path, {
flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true,
});
// create an Attachment document and upload file
let attachment;
try {
attachment = Attachment.createWithoutSave(pageId, user, fileStream, file.originalname, file.mimetype, file.size);
await fileUploadService.uploadFile(fileStream, attachment);
await attachment.save();
}
catch (err) {
// delete temporary file
fs.unlink(file.path, (err) => { if (err) { logger.error('Error while deleting tmp file.') } });
throw err;
}
return attachment;
}
async removeAllAttachments(attachments) {
const { fileUploadService } = this.crowi;
const attachmentsCollection = mongoose.connection.collection('attachments');
const unorderAttachmentsBulkOp = attachmentsCollection.initializeUnorderedBulkOp();
if (attachments.length === 0) {
return;
}
attachments.forEach((attachment) => {
unorderAttachmentsBulkOp.find({ _id: attachment._id }).remove();
});
await unorderAttachmentsBulkOp.execute();
await fileUploadService.deleteFiles(attachments);
return;
}
async removeAttachment(attachmentId) {
const Attachment = this.crowi.model('Attachment');
const { fileUploadService } = this.crowi;
const attachment = await Attachment.findById(attachmentId);
await fileUploadService.deleteFile(attachment);
await attachment.remove();
return;
}
} |
JavaScript | class TransactionView extends Component {
state = {
openTxInfo: false,
transactions: []
};
constructor(){
super();
this.handleTxInfoClose = this.handleTxInfoClose.bind(this);
}
handleTxInfoOpen = ( hash ) => {
this.setState({ openTxInfo: true, activeHash: hash });
}
handleTxInfoClose = () => {
this.setState({ openTxInfo: false });
}
async loadData(){
let contract = await contractHandlers.getMainContract( this.props.mainContractAddress );
if( contract == null || contract == undefined || contract.address == 0x0 || contract.address == '0x'){
this.setState({ isUndefined: true });
return;
}
let crowdsaleContract = await contractHandlers.getFirstCrowdsaleContract( contract.address );
if( crowdsaleContract == null ){
return;
}
let transactions = [];
let response = await axios({
method: 'POST',
dataType: 'json',
url: 'http://localhost:3000/addr/crowd',
data: {
ca: crowdsaleContract.address,
addr: this.props.auth.address
}
}).catch( (error) => {
console.error(error);
response.data = {
data: []
}
});
let hashes = response.data.data;
for( var hash of hashes ){
let transaction = await web3.eth.getTransaction( hash[0] );
let block = await web3.eth.getBlock( transaction.blockNumber );
transactions.push({
hash: transaction.hash,
blockNumber: transaction.blockNumber,
from: transaction.from,
to: transaction.to,
timestamp: moment.unix(block.timestamp).format('lll'),
value: await web3._extend.utils.fromWei( transaction.value.toNumber() )
});
}
this.setState({ transactions: transactions });
}
async componentWillMount(){
await this.loadData();
}
render() {
if( this.state.isUndefined ){ return null; }
return (
<div className="detail-tranasations">
<Table className="transaction-table">
<TableHead>
<TableRow>
<TableCell> Transaction Hash </TableCell>
<TableCell> Block </TableCell>
<TableCell> Timestamp </TableCell>
<TableCell> From </TableCell>
<TableCell> To </TableCell>
<TableCell> Amount </TableCell>
</TableRow>
</TableHead>
{
this.state.transactions.length == 0 ? (
<TableBody><TableRow><TableCell align="center" colSpan={6}> There is no transaction. </TableCell></TableRow></TableBody>
) : null
}
{
this.state.transactions.map((item, index) => {
return (
<TableBody key={index}>
<TableRow>
<TableCell className="tx-list" align="center">
<a href="#" onClick={this.handleTxInfoOpen.bind(this, item.hash)}>{item.hash}</a>
</TableCell>
<TableCell className="tx-list"> {item.blockNumber} </TableCell>
<TableCell className="tx-list timestamp"> {item.timestamp} </TableCell>
<TableCell className="tx-list"> {item.from} </TableCell>
<TableCell className="tx-list"> {item.to} </TableCell>
<TableCell className="tx-list"> {item.value} </TableCell>
</TableRow>
</TableBody>
);
})
}
</Table>
<Dialog
maxWidth={false}
open={this.state.openTxInfo}
onClose={this.handleTxInfoClose} >
<Transaction closeAction={this.handleTxInfoClose} hash={this.state.activeHash} />
</Dialog>
</div>
);
}
} |
JavaScript | class Config {
@observable isCreate = false
// 完整创建路径
@observable createPath = ''
// 最近打开项目
@observable historyProject = []
// 系统类型
@observable sysType = ''
/**
* 电路板类型
*/
@observable boardType = defaultBoardType
/**
* 项目类型
*/
@observable projectType = defaultProjectType
constructor(rootStore) {
this.rootStore = rootStore
}
@action setIsCreate(isCreate) {
this.isCreate = isCreate
}
@action initDefaultPath() {
this.createPath = this.rootStore.window.getDefaultPath()
}
@action selectPath() {
this.rootStore.window.selectDir((folder) => {
this.createPath = Array.isArray(folder) ? folder[0] : folder
})
}
@action setCreatePath(path) {
this.createPath = path
}
@action createProject() {
console.log('emit mobx createProject')
this.rootStore.window.createProject(this.createPath, this.projectType, this.boardType)
}
@action openExistingProject() {
this.rootStore.window.openExistingProject()
}
@action setHistoryPorject(historyProject) {
this.historyProject = historyProject
.map(item => ({
...item,
}))
.reverse()
}
@action openProject(projectFile) {
this.rootStore.window.openProject(projectFile)
}
@action setSysType(sysType) {
this.sysType = sysType
}
/**
* 设置电路板类型
* @param {*} boardType
*/
@action setBoardType(boardType) {
this.boardType = boardType
}
/**
* 设置项目类型
* @param {*} projectType
*/
@action setProjectType(projectType) {
this.projectType = projectType
}
} |
JavaScript | class SfbWebsiteApiCourses extends SfbWebsiteApiBase {
/**
* Constructor
*/
constructor() {
super();
this.uri = 'gymnastik/api';
}
} |
JavaScript | class Pattern {
/**
* Set up a pattern with only
* the length of dots to link
* @param {Number} dotLength Length of the pattern
*/
constructor (dotLength) {
this.dotLength = dotLength
this.suite = []
}
/**
* Fill the current instance with random values
*/
fillRandomly () {
while (!this.isComplete()) {
this.addDot(Math.floor(Math.random() * 9))
}
}
/**
* Add point to the current pattern
* @param {int} dotIndex Dot index to add
* @return boolean True if successfully added
*/
addDot (dotIndex) {
// Test if the dot can be added
if (this.isComplete() || ~this.suite.indexOf(dotIndex))
return [];
// Test for potential median dot
let lastDot = this.suite[this.suite.length - 1],
medianDot = (lastDot + dotIndex) / 2
if (lastDot != undefined &&
medianDot >> 0 === medianDot &&
(lastDot%3) - (medianDot%3) === (medianDot%3) - (dotIndex%3) &&
Math.floor(lastDot/3) - Math.floor(medianDot/3) === Math.floor(medianDot/3) - Math.floor(dotIndex/3)) {
let addedPoints = this.addDot(medianDot)
if (!this.isComplete()) {
this.suite.push(dotIndex)
addedPoints.push(dotIndex)
}
return addedPoints
}
this.suite.push(dotIndex)
return [dotIndex]
}
/**
* Checks if the instance suite is complete
* @return {Boolean}
*/
isComplete () {
return this.suite.length >= this.dotLength
}
/**
* Checks if a dot is already in the pattern
* @param {int} dotIndex Index to check
* @return {boolean}
*/
gotDot (dotIndex) {
return ~this.suite.indexOf(dotIndex)
}
/**
* Compare a pattern with the current instance.
* The output will be an array of three values:
* [0]: Number of dots in the right place in the pattern
* [1]: Number of correct dots badly placed in the pattern
* [2]: Number of wrong dots
* @param {Pattern} pattern Pattern to compare
* @return {Array}
*/
compare (pattern) {
var goodPos = 0,
wrongPos = 0
for (let i = 0; i < this.dotLength; i++) {
if (this.suite[i] === pattern.suite[i])
goodPos++
for (let j = 0; j < this.dotLength; j++) {
if (this.suite[j] === pattern.suite[i])
wrongPos++
}
}
return [goodPos, wrongPos - goodPos, this.dotLength - wrongPos]
}
/**
* Reset the pattern by removing all the dots
*/
reset () {
this.suite = []
}
} |
JavaScript | class AbstractComponent {
/**
* @param {PhotoSphereViewer | module:components.AbstractComponent} parent
* @param {string} className - CSS class added to the component's container
*/
constructor(parent, className) {
/**
* @summary Reference to main controller
* @type {PhotoSphereViewer}
* @readonly
*/
this.psv = parent instanceof PhotoSphereViewer ? parent : parent.psv;
/**
* @member {PhotoSphereViewer|module:components.AbstractComponent}
* @readonly
*/
this.parent = parent;
this.parent.children.push(this);
/**
* @summary All child components
* @type {module:components.AbstractComponent[]}
* @readonly
* @package
*/
this.children = [];
/**
* @summary Internal properties
* @member {Object}
* @protected
* @property {boolean} visible - Visibility of the component
*/
this.prop = {
visible: true,
};
/**
* @member {HTMLElement}
* @readonly
*/
this.container = document.createElement('div');
this.container.className = className;
this.parent.container.appendChild(this.container);
}
/**
* @summary Destroys the component
* @protected
*/
destroy() {
this.parent.container.removeChild(this.container);
this.children.forEach(child => child.destroy());
this.children.length = 0;
delete this.container;
delete this.parent;
delete this.psv;
delete this.prop;
}
/**
* @summary Refresh UI
* Must be be a very lightweight operation
* @package
*/
refresh() {
this.children.every((child) => {
child.refresh();
return this.psv.prop.uiRefresh === true;
});
}
/**
* @summary Displays or hides the component
*/
toggle() {
if (this.isVisible()) {
this.hide();
}
else {
this.show();
}
}
/**
* @summary Hides the component
*/
hide() {
this.container.style.display = 'none';
this.prop.visible = false;
}
/**
* @summary Displays the component
*/
show() {
this.container.style.display = '';
this.prop.visible = true;
}
/**
* @summary Check if the component is visible
* @returns {boolean}
*/
isVisible() {
return this.prop.visible;
}
} |
JavaScript | class ProportionConstraintField extends Component {
constructor(props) {
super(props);
const childrenArray = Children.toArray(props.children);
if (childrenArray.length !== 2) {
throw new Error('ProportionConstraintField must be passed two children -- one field for each value');
}
this.handlePresetSelect = this.handlePresetSelect.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.state = { hasFocus: false };
}
componentDidMount() {
this.componentDidUpdate(this.props);
}
componentDidUpdate(newProps) {
// Let invalid values stand if the user is currently editing the fields
if (!this.state.hasFocus) {
// Make sure our initial dimensions are initialised to something sensible
const { current: { width } } = newProps;
const value = parseInt(width, 10);
if (!value || value <= 0) {
this.resetDimensions();
}
}
}
/**
* Handle change events for the fields
* @param {Number} childIndex Index of the field that has been changed
* @param {String} newValue
*/
handleChange(childIndex, e, newValue) {
// If the new value can be converted to something sensible
const value = parseInt((newValue || (e.target && e.target.value)), 10);
if (value && value > 0) {
this.syncFields(childIndex, value);
}
}
/**
* Sync up the two fields
* @param {Number} childIndex Index of the field that has been changed
* @param {Number} newValue
*/
syncFields(childIndex, newValue) {
const { children, active, onAutofill, data: { ratio } } = this.props;
// value depends on whether onChange triggered on a basic input
// or a redux form input
const peerIndex = (childIndex === 0) ? 1 : 0;
const currentName = children[childIndex].props.name;
const peerName = children[peerIndex].props.name;
const multiplier = childIndex === 0 ? 1 / ratio : ratio;
onAutofill(currentName, newValue);
// retain aspect ratio only when this field is active
if (active) {
onAutofill(peerName, Math.round(newValue * multiplier));
}
}
/**
* Handle selection of a preset image
* @param {Number} newWidth
*/
handlePresetSelect(newWidth) {
this.syncFields(0, newWidth);
// Reset the focus on the Width field
const { key } = this.props.children[0];
const fieldEl = document.getElementById(key);
if (fieldEl) {
fieldEl.focus();
}
}
/**
* Handle the user moving to another field
* @param {Number} key Index of the field being blured
* @param {Event} e
*/
handleBlur(key, e) {
this.setState({ hasFocus: false });
const newValue = parseInt(e && e.target && e.target.value, 10);
if (!newValue || newValue <= 0) {
// If the user leave the field in an invalid state, reset dimensions to their default
e.preventDefault();
this.resetDimensions();
}
}
/**
* Handle the focus on a field
*/
handleFocus() {
this.setState({ hasFocus: true });
}
/**
* Get the default width for images who don't have a valid one yet.
* @returns {number}
*/
defaultWidth() {
const { imageSizePresets, data: { originalWidth } } = this.props;
// Default to the default image size preset first. Then to the original width of the image.
// If all else fail, default to 600
const defaultPreset = imageSizePresets && imageSizePresets.find(preset => preset.default);
const defaultWidth = (defaultPreset && defaultPreset.width) || originalWidth || 600;
// Make sure our default width isn't wider than the natural width of the image
return originalWidth && originalWidth < defaultWidth ? originalWidth : defaultWidth;
}
/**
* Reset the dimensions to a sensible dimensions.
*/
resetDimensions() {
const defaultValue = this.defaultWidth();
this.syncFields(0, defaultValue);
}
render() {
const {
FieldGroup,
data: { originalWidth, isRemoteFile },
current: { width: currentWidth },
imageSizePresets } = this.props;
return (
<Fragment>
<FieldGroup smallholder={false} {...this.props}>
{this.props.children.map((child, key) => (
cloneElement(child, {
// overload the children change handler
onChange: (e, newValue) => this.handleChange(key, e, newValue),
onBlur: (e) => this.handleBlur(key, e),
onFocus: () => this.handleFocus(),
key,
}, child.props.children)
))}
{!isRemoteFile && <ImageSizePresetList
originalWidth={parseInt(originalWidth, 10)}
currentWidth={currentWidth}
imageSizePresets={imageSizePresets}
onSelect={this.handlePresetSelect}
/>
}
</FieldGroup>
</Fragment>
);
}
} |
JavaScript | class Motorcyle{
constructor(name, wheels) {
this.name = name,
this.wheels = wheels;
};
wheelie() {
console.log('Wheee!');
return 'Wheee!';
};
drive() {
super.stop();
};
stop() {
console.log('Stopping');
return 'Stopping';
};
} |
JavaScript | class RasterSourceEvent extends Event {
/**
* @param {string} type Type.
* @param {import("../PluggableMap.js").FrameState} frameState The frame state.
* @param {Object} data An object made available to operations.
*/
constructor(type, frameState, data) {
super(type);
/**
* The raster extent.
* @type {import("../extent.js").Extent}
* @api
*/
this.extent = frameState.extent;
/**
* The pixel resolution (map units per pixel).
* @type {number}
* @api
*/
this.resolution = frameState.viewState.resolution / frameState.pixelRatio;
/**
* An object made available to all operations. This can be used by operations
* as a storage object (e.g. for calculating statistics).
* @type {Object}
* @api
*/
this.data = data;
}
} |
JavaScript | class RasterSource extends ImageSource {
/**
* @param {Options} options Options.
*/
constructor(options) {
super({
projection: null
});
/**
* @private
* @type {*}
*/
this.worker_ = null;
/**
* @private
* @type {RasterOperationType}
*/
this.operationType_ = options.operationType !== undefined ?
options.operationType : RasterOperationType.PIXEL;
/**
* @private
* @type {number}
*/
this.threads_ = options.threads !== undefined ? options.threads : 1;
/**
* @private
* @type {Array<import("../layer/Layer.js").default>}
*/
this.layers_ = createLayers(options.sources);
for (let i = 0, ii = this.layers_.length; i < ii; ++i) {
listen(this.layers_[i], EventType.CHANGE, this.changed, this);
}
/**
* @private
* @type {import("../TileQueue.js").default}
*/
this.tileQueue_ = new TileQueue(function() {
return 1;
}, this.changed.bind(this));
/**
* The most recently requested frame state.
* @type {import("../PluggableMap.js").FrameState}
* @private
*/
this.requestedFrameState_;
/**
* The most recently rendered image canvas.
* @type {import("../ImageCanvas.js").default}
* @private
*/
this.renderedImageCanvas_ = null;
/**
* The most recently rendered revision.
* @type {number}
*/
this.renderedRevision_;
/**
* @private
* @type {import("../PluggableMap.js").FrameState}
*/
this.frameState_ = {
animate: false,
coordinateToPixelTransform: createTransform(),
extent: null,
focus: null,
index: 0,
layerStatesArray: getLayerStatesArray(this.layers_),
pixelRatio: 1,
pixelToCoordinateTransform: createTransform(),
postRenderFunctions: [],
size: [0, 0],
skippedFeatureUids: {},
tileQueue: this.tileQueue_,
time: Date.now(),
usedTiles: {},
viewState: /** @type {import("../View.js").State} */ ({
rotation: 0
}),
viewHints: [],
wantedTiles: {}
};
this.setAttributions(function(frameState) {
const attributions = [];
for (let index = 0, iMax = options.sources.length; index < iMax; ++index) {
const sourceOrLayer = options.sources[index];
const source = sourceOrLayer instanceof Source ? sourceOrLayer : sourceOrLayer.getSource();
const attributionGetter = source.getAttributions();
if (typeof attributionGetter === 'function') {
const sourceAttribution = attributionGetter(frameState);
attributions.push.apply(attributions, sourceAttribution);
}
}
return attributions.length !== 0 ? attributions : null;
});
if (options.operation !== undefined) {
this.setOperation(options.operation, options.lib);
}
}
/**
* Set the operation.
* @param {Operation} operation New operation.
* @param {Object=} opt_lib Functions that will be available to operations run
* in a worker.
* @api
*/
setOperation(operation, opt_lib) {
this.worker_ = new Processor({
operation: operation,
imageOps: this.operationType_ === RasterOperationType.IMAGE,
queue: 1,
lib: opt_lib,
threads: this.threads_
});
this.changed();
}
/**
* Update the stored frame state.
* @param {import("../extent.js").Extent} extent The view extent (in map units).
* @param {number} resolution The view resolution.
* @param {import("../proj/Projection.js").default} projection The view projection.
* @return {import("../PluggableMap.js").FrameState} The updated frame state.
* @private
*/
updateFrameState_(extent, resolution, projection) {
const frameState = /** @type {import("../PluggableMap.js").FrameState} */ (assign({}, this.frameState_));
frameState.viewState = /** @type {import("../View.js").State} */ (assign({}, frameState.viewState));
const center = getCenter(extent);
frameState.extent = extent.slice();
frameState.focus = center;
frameState.size[0] = Math.round(getWidth(extent) / resolution);
frameState.size[1] = Math.round(getHeight(extent) / resolution);
frameState.time = Date.now();
frameState.animate = false;
const viewState = frameState.viewState;
viewState.center = center;
viewState.projection = projection;
viewState.resolution = resolution;
return frameState;
}
/**
* Determine if all sources are ready.
* @return {boolean} All sources are ready.
* @private
*/
allSourcesReady_() {
let ready = true;
let source;
for (let i = 0, ii = this.layers_.length; i < ii; ++i) {
source = this.layers_[i].getSource();
if (source.getState() !== SourceState.READY) {
ready = false;
break;
}
}
return ready;
}
/**
* @inheritDoc
*/
getImage(extent, resolution, pixelRatio, projection) {
if (!this.allSourcesReady_()) {
return null;
}
const frameState = this.updateFrameState_(extent, resolution, projection);
this.requestedFrameState_ = frameState;
// check if we can't reuse the existing ol/ImageCanvas
if (this.renderedImageCanvas_) {
const renderedResolution = this.renderedImageCanvas_.getResolution();
const renderedExtent = this.renderedImageCanvas_.getExtent();
if (resolution !== renderedResolution || !equals(extent, renderedExtent)) {
this.renderedImageCanvas_ = null;
}
}
if (!this.renderedImageCanvas_ || this.getRevision() !== this.renderedRevision_) {
this.processSources_();
}
frameState.tileQueue.loadMoreTiles(16, 16);
if (frameState.animate) {
requestAnimationFrame(this.changed.bind(this));
}
return this.renderedImageCanvas_;
}
/**
* Start processing source data.
* @private
*/
processSources_() {
const frameState = this.requestedFrameState_;
const len = this.layers_.length;
const imageDatas = new Array(len);
for (let i = 0; i < len; ++i) {
const imageData = getImageData(this.layers_[i], frameState, frameState.layerStatesArray[i]);
if (imageData) {
imageDatas[i] = imageData;
} else {
return;
}
}
const data = {};
this.dispatchEvent(new RasterSourceEvent(RasterEventType.BEFOREOPERATIONS, frameState, data));
this.worker_.process(imageDatas, data, this.onWorkerComplete_.bind(this, frameState));
}
/**
* Called when pixel processing is complete.
* @param {import("../PluggableMap.js").FrameState} frameState The frame state.
* @param {Error} err Any error during processing.
* @param {ImageData} output The output image data.
* @param {Object} data The user data.
* @private
*/
onWorkerComplete_(frameState, err, output, data) {
if (err || !output) {
return;
}
// do nothing if extent or resolution changed
const extent = frameState.extent;
const resolution = frameState.viewState.resolution;
if (resolution !== this.requestedFrameState_.viewState.resolution ||
!equals(extent, this.requestedFrameState_.extent)) {
return;
}
let context;
if (this.renderedImageCanvas_) {
context = this.renderedImageCanvas_.getImage().getContext('2d');
} else {
const width = Math.round(getWidth(extent) / resolution);
const height = Math.round(getHeight(extent) / resolution);
context = createCanvasContext2D(width, height);
this.renderedImageCanvas_ = new ImageCanvas(extent, resolution, 1, context.canvas);
}
context.putImageData(output, 0, 0);
this.changed();
this.renderedRevision_ = this.getRevision();
this.dispatchEvent(new RasterSourceEvent(RasterEventType.AFTEROPERATIONS, frameState, data));
}
/**
* @override
*/
getImageInternal() {
return null; // not implemented
}
} |
JavaScript | class Task {
@tracked data = null;
@tracked errorReason = null;
@tracked isLoading = false;
get isError() {
return Boolean(this.errorReason);
}
get isSuccess() {
return Boolean(this.data);
}
} |
JavaScript | class TableHeightCommand extends TablePropertyCommand {
/**
* Creates a new `TableHeightCommand` instance.
*
* @param {module:core/editor/editor~Editor} editor An editor in which this command will be used.
* @param {String} defaultValue The default value of the attribute.
*/
constructor( editor, defaultValue ) {
super( editor, 'tableHeight', defaultValue );
}
/**
* @inheritDoc
*/
_getValueToSet( value ) {
value = addDefaultUnitToNumericValue( value, 'px' );
if ( value === this._defaultValue ) {
return null;
}
return value;
}
} |
JavaScript | class ActionDocument extends PastellAppelService {
/** Initalise une nouvelle instance de la classe 'ObtenirInformationsNode'.
* @param id_entite L'identifiant de l'entité.
* @param id_document L'identifiant du document. */
constructor(id_entite, id_document, action) {
super('POST', 'entite/'+id_entite+'/document/'+id_document+'/action/'+action);
}
/** Invoque le service. */
async appeler() {
// Appel du service
var retour = await super.appelSync();
var resultat = await retour.json();
// Vérification du retour service.
if(retour.status != 200 && retour.status != 201) throw resultat;
// Retour du résulat.
return resultat;
}
/** Invoque le service de manère asynchrone */
appelerAsync() {
// Intialisation des options.
var options = { method: super.obtenirMethode(), headers : super.obtenirHeaders() };
// Appel du service
var fetch = super.appelAsync();
fetch(super.obtenirHote()+super.obtenirService(), options)
.then(reponse => reponse.json())
.then(function(json) { return; })
.catch(function(erreur) { throw erreur; }); ;
}
} |
JavaScript | class Fields {
/**
* @param {Object} sdk An instance of the SDK so the module can communicate
* with other modules
* @param {Object} request An instance of the request module tied to this
* module's audience
* @param {string} baseUrl The base URL provided by the parent module
*/
constructor(sdk, request, baseUrl) {
this._baseUrl = baseUrl;
this._request = request;
this._sdk = sdk;
}
/**
* Gets information about a field
*
* API Endpoint: '/fields/:fieldId'
* Method: GET
*
* @param {Number} outputFieldId The ID of an output field
*
* @returns {Promise}
* @fulfill {OutputField} Information about the output field
* @reject {Error}
*
* @example
* contxtSdk.iot.fields
* .get(563)
* .then((outputField) => console.log(outputField))
* .catch((err) => console.log(err));
*/
get(outputFieldId) {
if (!outputFieldId) {
return Promise.reject(
new Error(
'An outputFieldId is required for getting information about an output field'
)
);
}
return this._request
.get(`${this._baseUrl}/fields/${outputFieldId}`)
.then((outputField) => toCamelCase(outputField));
}
} |
JavaScript | @Template(Button)
class mButton extends ViewModel {
@Property(String) label;
@Property(String) icon;
@Property(Boolean) disabled;
connected() {
this._rippleOff = Ripple.onclick(this.$el);
}
disconnected() {
this._rippleOff();
}
_computeClass() {
const attrs = this.$attrs;
const classNames = [
'qm-Button--'+(attrs.variant || 'flat')
];
if (!this.label && this.icon) classNames.push('qm-Button--icon');
if (attrs.size) classNames.push('qm-Button--'+attrs.size);
if (attrs.rounded) classNames.push('qm-Button--round');
if (attrs.floating) classNames.push('qm-Button--floating');
return classNames;
}
get _iconSize() {
var size = this.$attrs.size;
if (this.label) { // text and icon
return size === 'large' ? size : 'small';
} else { // only icon - preserve the size
return size ? size : 'normal';
}
}
} |
JavaScript | class TinymceInlineToolbar {
/**
* @param {Object} editor Tinymce editor instance
* @param {Array} buttons Array of button literal object
*/
constructor(editor, buttons) {
this.mceIframe = document.getElementById(`${editor.id}_ifr`);
this.container = editor.getContainer();
this.mceToolbar = null;
this.mceStatusbar = null;
if (this.container) {
this.mceToolbar = this.container.querySelector('.mce-toolbar-grp');
this.mceStatusbar = this.container.querySelector('.mce-statusbar');
}
// type: tinymce.ui.Control
this.control = tinymce.ui.Factory.create({
type: 'panel',
classes: 'inline-toolbar',
layout: 'stack',
items: [
{
type: 'toolbar',
items: buttons,
},
],
});
}
remove() {
this.control.remove();
return this;
}
hide() {
this.control.hide();
return this;
}
show() {
this.control.show();
return this;
}
renderTo(dom) {
this.control.renderTo(dom);
return this;
}
setStyles(styles) {
tinymce.DOM.setStyles(this.control.getEl(), styles);
return this;
}
/**
* Source: https://github.com/Automattic/wp-calypso/blob/desktop/2.6.0/client/components/tinymce/plugins/wpcom/plugin.js
*/
reposition(currSelection) {
if (!currSelection) {
return this;
}
const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const iframeRect = this.mceIframe ? this.mceIframe.getBoundingClientRect() : {
top: 0,
right: windowWidth,
bottom: windowHeight,
left: 0,
width: windowWidth,
height: windowHeight,
};
const toolbarEl = this.control.getEl();
const toolbarWidth = toolbarEl.offsetWidth;
const toolbarHeight = toolbarEl.offsetHeight;
const selection = currSelection.getBoundingClientRect();
const selectionMiddle = (selection.left + selection.right) / 2;
const buffer = 5;
const margin = 8;
const spaceNeeded = toolbarHeight + margin + buffer;
const mceToolbarBottom = this.mceToolbar ?
this.mceToolbar.getBoundingClientRect().bottom : 0;
const mceStatusbarTop = this.mceStatusbar ?
windowHeight - this.mceStatusbar.getBoundingClientRect().top : 0;
const blockedTop = Math.max(0, mceToolbarBottom, iframeRect.top);
const blockedBottom = Math.max(0, mceStatusbarTop, windowHeight - iframeRect.bottom);
const spaceTop = (selection.top + iframeRect.top) - blockedTop;
const spaceBottom = windowHeight - iframeRect.top - selection.bottom - blockedBottom;
const editorHeight = windowHeight - blockedTop - blockedBottom;
const topOffset = 10;
let className = '';
let top = 0;
let left = 0;
if (spaceTop >= editorHeight || spaceBottom >= editorHeight) {
return this.hide();
}
if (this.bottom) {
if (spaceBottom >= spaceNeeded) {
className = ' mce-arrow-up';
top = selection.bottom + iframeRect.top + scrollY + topOffset;
} else if (spaceTop >= spaceNeeded) {
className = ' mce-arrow-down';
top = (selection.top + iframeRect.top + scrollY) - toolbarHeight - margin;
}
} else if (spaceTop >= spaceNeeded) {
className = ' mce-arrow-down';
top = (selection.top + iframeRect.top + scrollY) - toolbarHeight - margin;
} else if (
spaceBottom >= spaceNeeded &&
editorHeight / 2 > (selection.bottom + iframeRect.top) - blockedTop
) {
className = ' mce-arrow-up';
top = selection.bottom + iframeRect.top + scrollY + topOffset;
}
if (typeof top === 'undefined') {
top = scrollY + blockedTop + buffer;
}
left = (selectionMiddle - (toolbarWidth / 2)) + iframeRect.left + scrollX;
if (selection.left < 0 || selection.right > iframeRect.width) {
left = iframeRect.left + scrollX + ((iframeRect.width - toolbarWidth) / 2);
} else if (toolbarWidth >= windowWidth) {
className += ' mce-arrow-full';
left = 0;
} else if (
(left < 0 && selection.left + toolbarWidth > windowWidth) ||
(left + toolbarWidth > windowWidth && selection.right - toolbarWidth < 0)
) {
left = (windowWidth - toolbarWidth) / 2;
} else if (left < iframeRect.left + scrollX) {
className += ' mce-arrow-left';
left = selection.left + iframeRect.left + scrollX;
} else if (left + toolbarWidth > iframeRect.width + iframeRect.left + scrollX) {
className += ' mce-arrow-right';
left = (selection.right - toolbarWidth) + iframeRect.left + scrollX;
}
toolbarEl.className = toolbarEl.className.replace(/ ?mce-arrow-[\w]+/g, '') + className;
this.setStyles({ left, top });
return this;
}
} |
JavaScript | class DeploymentPropertiesExtended {
constructor() {
}
/**
* Defines the metadata of DeploymentPropertiesExtended
*
* @returns {object} metadata of DeploymentPropertiesExtended
*
*/
mapper() {
return {
required: false,
serializedName: 'DeploymentPropertiesExtended',
type: {
name: 'Composite',
className: 'DeploymentPropertiesExtended',
modelProperties: {
provisioningState: {
required: false,
readOnly: true,
serializedName: 'provisioningState',
type: {
name: 'String'
}
},
correlationId: {
required: false,
readOnly: true,
serializedName: 'correlationId',
type: {
name: 'String'
}
},
timestamp: {
required: false,
readOnly: true,
serializedName: 'timestamp',
type: {
name: 'DateTime'
}
},
outputs: {
required: false,
serializedName: 'outputs',
type: {
name: 'Object'
}
},
providers: {
required: false,
serializedName: 'providers',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ProviderElementType',
type: {
name: 'Composite',
className: 'Provider'
}
}
}
},
dependencies: {
required: false,
serializedName: 'dependencies',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'DependencyElementType',
type: {
name: 'Composite',
className: 'Dependency'
}
}
}
},
template: {
required: false,
serializedName: 'template',
type: {
name: 'Object'
}
},
templateLink: {
required: false,
serializedName: 'templateLink',
type: {
name: 'Composite',
className: 'TemplateLink'
}
},
parameters: {
required: false,
serializedName: 'parameters',
type: {
name: 'Object'
}
},
parametersLink: {
required: false,
serializedName: 'parametersLink',
type: {
name: 'Composite',
className: 'ParametersLink'
}
},
mode: {
required: false,
serializedName: 'mode',
type: {
name: 'Enum',
allowedValues: [ 'Incremental', 'Complete' ]
}
},
debugSetting: {
required: false,
serializedName: 'debugSetting',
type: {
name: 'Composite',
className: 'DebugSetting'
}
}
}
}
};
}
} |
JavaScript | class RootElement extends Component {
componentDidMount() {
console.timeStamp('RootElement DidMount');
this.unsubscribe = Dispatcher.on('RenderView', () => {
return this.setState({ts: _.now()});
});
Router.start();
}
componentWillUnmount() {
super.componentWillUnmount();
this.unsubscribe();
}
} |
JavaScript | class FormField {
// Element type for the form field
static get TEXT_FIELD() { return 'TEXT_FIELD'; }
static get TEXT_AREA() { return 'TEXT_AREA'; }
static get SELECT_FIELD() { return 'SELECT_FIELD'; }
static get HTML_CONTENT() { return 'HTML_CONTENT'; }
static get FILE_UPLOAD() { return 'FILE_UPLOAD'; }
// Validation method constants
static REQUIRED_VALIDATION(input) { return !!input; } // Required field
static LENGTH_VALIDATION(input, size) { return input.length >= size; } // Max size
static EMAIL_VALIDATION(email) {return EMAIL_REGEX.test(email); } // Email validation
static NO_VALIDATION() { return true; } // No validation field
// Default error messages
static get DEFAULT_ERROR_MESSAGES() {
return {
required: 'This field is required',
email: 'The email you entered is invalid',
default: 'Something went wrong',
};
}
/**
* Validation function getter
* @param {String} type Validation identifier
* @return {Function} Validation function
*/
static getValidationFn(type='') {
// Convention: Validation function ends with a `_VALIDATION`.
const key = type.toUpperCase() + '_VALIDATION';
return FormField[key] || FormField.NO_VALIDATION;
}
/**
* Error message getter
* @return {String}
*/
get ERROR_MESSAGE() {
const type = this.attribs.validationType;
return FormField.DEFAULT_ERROR_MESSAGES[type] ||
FormField.DEFAULT_ERROR_MESSAGES['default'];
}
// Constructor
constructor(type, id, attribs={}) {
this.id = id;
this.type = type;
this.attribs = attribs;
this.selector = `.js-form-input-el--${this.id}`;
// Get validation function
const validationFn = FormField.getValidationFn(this.attribs.validationType);
this.validate = () => validationFn(this.$inputEl.value);
}
/**
* Render and get the element
* @param {Object} attribs Attributes/Props
* @param {Boolean} merge To merge or not to merge the attributes
* @return {HTMLElement} Rendered element
*/
getElement(attribs=this.attribs, merge=true) {
// Merge the config
if(merge) {
attribs = assign(this.attribs, attribs);
}
let elementName = 'input';
let childrenEls = null;
let isInput = true;
// Configure the element depending on its type
switch(this.type) {
case FormField.TEXT_FIELD: {
elementName = 'input';
attribs.type = 'text';
break;
}
case FormField.TEXT_AREA: {
elementName = 'textarea';
break;
}
case FormField.SELECT_FIELD: {
elementName = 'select';
childrenEls = attribs.options_;
break;
}
case FormField.HTML_CONTENT: {
elementName = 'div';
attribs.style = 'padding: 0 1em;';
isInput = false;
break;
}
case FormField.FILE_UPLOAD: {
elementName = 'input';
attribs.type = 'file';
break;
}
}
attribs.name = attribs.name || this.id;
// If the element has children, render them
if(childrenEls && childrenEls.length) {
childrenEls =
childrenEls
.filter(elem => elem.textContent || elem.innerHTML)
.map(elem => vdom.createElem(elem.tagname, elem));
} else {
childrenEls = [];
}
const $inputEl = vdom.createElem(elementName, attribs, childrenEls);
$inputEl.classList.add(this.selector);
// For inputs, add the form control class
if(isInput) $inputEl.classList.add('form-control');
this.$inputEl = $inputEl;
return $inputEl;
}
/**
* Get template fields
* (Static version of the instance method)
*/
static getTemplateFields(type) {
return FormField.prototype.getTemplateFields(type);
}
/**
* Get template fields
* @param {String} type The element type (default:this.type)
* @return {Object} The element template
*/
getTemplateFields(type=this.type) {
const template = { label: 'Some content' };
// Extend the attributes
switch(type) {
case FormField.TEXT_FIELD: {
assign(template, {
placeholder: 'Eg - Wowness',
label: 'Enter value',
validationType: 'required',
});
break;
}
case FormField.TEXT_AREA: {
assign(template, {
placeholder: 'Eg - Something cool',
label: 'Enter value',
validationType: 'required',
});
break;
}
case FormField.SELECT_FIELD: {
assign(template, {
options_: [],
label: 'Select Value',
validationType: 'required',
});
break;
}
case FormField.FILE_UPLOAD: {
assign(template, {
label: 'Upload image',
validationType: 'required',
});
break;
}
case FormField.HTML_CONTENT: {
assign(template, {
innerHTML: 'This is content!',
});
break;
}
}
return template;
}
/**
* Mark the field as invalid (after validation)
* @param {String} text
*/
markInvalid(text = 'The value you entered is invalid') {
this.unmark();
this.$invalidMessage = vdom.div({}, [ text ]);
this.$inputEl.style.borderColor = this.$invalidMessage.style.color = '#e74c3c';
this.$inputEl.parentNode.appendChild(this.$invalidMessage);
}
/**
* Unmark the field(if not invalid)
*/
unmark() {
if(this.$invalidMessage) {
try {
this.$inputEl.parentNode.removeChild(this.$invalidMessage);
this.$inputEl.style.borderColor = '#ddd';
this.$invalidMessage = null;
} catch(e) { console.log(e); }
}
}
} |
JavaScript | class Plane extends Molecule {
/**
* Creates a new `Plane`. Properties from the `initialOptions` parameter
* are applied to this Plane's [famous/src/core/Surface](#famous/src/core/Surface) as well as to
* to this Plane's [famous/src/core/Modifier](#famous/src/core/Modifier), hence the API of a Plane
* is currently the combination of the Famo.us `Modifier` and `Surface` APIs.
*
* @constructor
* @param {Object} initialOptions Options for the new Plane.
*/
constructor(initialOptions) {
super(initialOptions);
this.surface = new Surface(this.options);
this.add(this.surface);
this.surface.pipe(this.options.handler);
}
/**
* Get the content of this Plane's [famous/src/core/Surface](#famous/src/core/Surface).
* See [famous/src/core/Surface.getContent](#famous/src/core/Surface.getContent).
*/
getContent() {
const args = Array.prototype.splice.call(arguments, 0);
return this.surface.getContent.apply(this.surface, args);
}
/**
* Set the content of this Plane's [famous/src/core/Surface](#famous/src/core/Surface).
* See [famous/src/core/Surface.setContent](#famous/src/core/Surface.setContent).
*/
setContent() {
const args = Array.prototype.splice.call(arguments, 0);
return this.surface.setContent.apply(this.surface, args);
}
} |
JavaScript | class ChannelDelete extends Event {
constructor(...args) {
super(...args, {
dirname: __dirname,
});
}
/**
* Function for recieving event.
* @param {bot} bot The instantiating client
* @param {GuildChannel|DMChannel} channel The channel that was deleted
* @readonly
*/
async run(bot, channel) {
// For debugging
if (bot.config.debug) bot.logger.debug(`Channel: ${channel.type == 'dm' ? channel.recipient.tag : channel.name} has been deleted${channel.type == 'dm' ? '' : ` in guild: ${channel.guild.id}`}. (${types[channel.type]})`);
// Don't really know but a check for DM must be made
if (channel.type == 'dm') return;
// Get server settings / if no settings then return
const settings = channel.guild.settings;
if (Object.keys(settings).length == 0) return;
// IF it's a ticket channel and TICKET logging is enabled then don't show CHANNELDELETE log
const regEx = /ticket-\d{18}/g;
if (regEx.test(channel.name) && settings.ModLogEvents?.includes('TICKET')) return bot.emit('ticketClose', channel);
// Check if event channelDelete is for logging
if (settings.ModLogEvents?.includes('CHANNELDELETE') && settings.ModLog) {
const embed = new Embed(bot, channel.guild)
.setDescription(`**${types[channel.type]} channel deleted: ${'#' + channel.name}**`)
.setColor(15158332)
.setFooter(`ID: ${channel.id}`)
.setAuthor(bot.user.username, bot.user.displayAvatarURL())
.setTimestamp();
// Find channel and send message
try {
const modChannel = await bot.channels.fetch(settings.ModLogChannel).catch(() => bot.logger.error(`Error fetching guild: ${channel.guild.id} logging channel`));
if (modChannel && modChannel.guild.id == channel.guild.id) bot.addEmbed(modChannel.id, [embed]);
} catch (err) {
bot.logger.error(`Event: '${this.conf.name}' has error: ${err.message}.`);
}
}
}
} |
JavaScript | class CdkTreeNestedExample {
constructor() {
this.treeControl = new NestedTreeControl(node => node.children);
this.dataSource = new ArrayDataSource(TREE_DATA);
this.hasChild = (_, node) => !!node.children && node.children.length > 0;
}
} |
JavaScript | class CheerioCrawler {
/**
* @param {CheerioCrawlerOptions} options
* All `CheerioCrawler` parameters are passed via an options object.
*/
constructor(options = {}) {
const {
requestOptions,
handlePageFunction,
requestTimeoutSecs = 30,
handlePageTimeoutSecs = 60,
ignoreSslErrors = true,
additionalMimeTypes = [],
suggestResponseEncoding,
forceResponseEncoding,
proxyConfiguration,
// Autoscaled pool shorthands
minConcurrency,
maxConcurrency,
// Basic crawler options
requestList,
requestQueue,
maxRequestRetries,
maxRequestsPerCrawl,
handleFailedRequestFunction = this._defaultHandleFailedRequestFunction.bind(this),
autoscaledPoolOptions = DEFAULT_AUTOSCALED_POOL_OPTIONS,
prepareRequestFunction,
useSessionPool = false,
sessionPoolOptions = {},
persistCookiesPerSession = false,
} = options;
checkParamOrThrow(handlePageFunction, 'options.handlePageFunction', 'Function');
checkParamOrThrow(requestOptions, 'options.requestOptions', 'Maybe Object');
checkParamOrThrow(requestTimeoutSecs, 'options.requestTimeoutSecs', 'Number');
checkParamOrThrow(handlePageTimeoutSecs, 'options.handlePageTimeoutSecs', 'Number');
checkParamOrThrow(ignoreSslErrors, 'options.ignoreSslErrors', 'Maybe Boolean');
checkParamOrThrow(prepareRequestFunction, 'options.prepareRequestFunction', 'Maybe Function');
checkParamOrThrow(additionalMimeTypes, 'options.additionalMimeTypes', '[String]');
checkParamOrThrow(suggestResponseEncoding, 'options.suggestResponseEncoding', 'Maybe String');
checkParamOrThrow(forceResponseEncoding, 'options.forceResponseEncoding', 'Maybe String');
checkParamOrThrow(useSessionPool, 'options.useSessionPool', 'Boolean');
checkParamOrThrow(sessionPoolOptions, 'options.sessionPoolOptions', 'Object');
checkParamOrThrow(persistCookiesPerSession, 'options.persistCookiesPerSession', 'Boolean');
checkParamPrototypeOrThrow(proxyConfiguration, 'options.proxyConfiguration', ProxyConfiguration, 'ProxyConfiguration', true);
this.log = defaultLog.child({ prefix: 'CheerioCrawler' });
if (persistCookiesPerSession && !useSessionPool) {
throw new Error('Cannot use "options.persistCookiesPerSession" without "options.useSessionPool"');
}
this.supportedMimeTypes = new Set(DEFAULT_MIME_TYPES);
if (additionalMimeTypes.length) this._extendSupportedMimeTypes(additionalMimeTypes);
if (requestOptions) {
// DEPRECATED 2020-03-22
this.requestOptions = requestOptions;
this.log.deprecated('options.requestOptions is deprecated. Use options.prepareRequestFunction instead.');
}
if (suggestResponseEncoding && forceResponseEncoding) {
this.log.warning('Both forceResponseEncoding and suggestResponseEncoding options are set. Using forceResponseEncoding.');
}
this.handlePageFunction = handlePageFunction;
this.handlePageTimeoutMillis = handlePageTimeoutSecs * 1000;
this.requestTimeoutMillis = requestTimeoutSecs * 1000;
this.ignoreSslErrors = ignoreSslErrors;
this.suggestResponseEncoding = suggestResponseEncoding;
this.forceResponseEncoding = forceResponseEncoding;
this.prepareRequestFunction = prepareRequestFunction;
this.proxyConfiguration = proxyConfiguration;
this.persistCookiesPerSession = persistCookiesPerSession;
this.useSessionPool = useSessionPool;
this.sessionPoolOptions = sessionPoolOptions;
/** @ignore */
this.basicCrawler = new BasicCrawler({
// Basic crawler options.
requestList,
requestQueue,
maxRequestRetries,
maxRequestsPerCrawl,
handleRequestFunction: (...args) => this._handleRequestFunction(...args),
handleRequestTimeoutSecs: handlePageTimeoutSecs * BASIC_CRAWLER_TIMEOUT_MULTIPLIER,
handleFailedRequestFunction,
proxyConfiguration,
// Autoscaled pool options.
minConcurrency,
maxConcurrency,
autoscaledPoolOptions,
// Session pool options
sessionPoolOptions: this.sessionPoolOptions,
useSessionPool: this.useSessionPool,
// log
log: this.log,
});
this.isRunningPromise = null;
}
/**
* Runs the crawler. Returns promise that gets resolved once all the requests got processed.
*
* @return {Promise<void>}
*/
async run() {
if (this.isRunningPromise) return this.isRunningPromise;
this.isRunningPromise = this.basicCrawler.run();
this.autoscaledPool = this.basicCrawler.autoscaledPool;
await this.isRunningPromise;
}
/**
* **EXPERIMENTAL**
* Function for attaching CrawlerExtensions such as the Unblockers.
* @param {CrawlerExtension} extension - Crawler extension that overrides the crawler configuration.
*/
use(extension) {
const inheritsFromCrawlerExtension = extension instanceof CrawlerExtension;
if (!inheritsFromCrawlerExtension) {
throw new Error('Object passed to the "use" method does not inherit from the "CrawlerExtension" abstract class.');
}
const extensionOptions = extension.getCrawlerOptions();
for (const [key, value] of Object.entries(extensionOptions)) {
const isConfigurable = this.hasOwnProperty(key); // eslint-disable-line
const originalType = typeof this[key];
const extensionType = typeof value; // What if we want to null something? It is really needed?
const isSameType = originalType === extensionType || value == null; // fast track for deleting keys
const exists = this[key] != null;
if (!isConfigurable) { // Test if the property can be configured on the crawler
throw new Error(`${extension.name} tries to set property "${key}" that is not configurable on CheerioCrawler instance.`);
}
if (!isSameType && exists) { // Assuming that extensions will only add up configuration
throw new Error(
`${extension.name} tries to set property of different type "${extensionType}". "CheerioCrawler.${key}: ${originalType}".`,
);
}
this.log.warning(`${extension.name} is overriding "CheerioCrawler.${key}: ${originalType}" with ${value}.`);
this[key] = value;
}
}
/**
* Wrapper around handlePageFunction that opens and closes pages etc.
*
* @param {Object} options
* @param {Request} options.request
* @param {AutoscaledPool} options.autoscaledPool
* @param {Session} [options.session]
* @ignore
*/
async _handleRequestFunction({ request, autoscaledPool, session }) {
let proxyInfo;
let proxyUrl;
if (this.proxyConfiguration) {
proxyInfo = this.proxyConfiguration.newProxyInfo(session ? session.id : undefined);
proxyUrl = proxyInfo.url;
}
if (this.prepareRequestFunction) await this.prepareRequestFunction({ request, session, proxyInfo });
const { dom, isXml, body, contentType, response } = await addTimeoutToPromise(
this._requestFunction({ request, session, proxyUrl }),
this.requestTimeoutMillis,
`request timed out after ${this.requestTimeoutMillis / 1000} seconds.`,
);
if (this.useSessionPool) {
this._throwOnBlockedRequest(session, response.statusCode);
}
if (this.persistCookiesPerSession) {
session.setCookiesFromResponse(response);
}
request.loadedUrl = response.url;
const { log } = this;
const $ = dom ? cheerio.load(dom, { xmlMode: isXml }) : null;
const context = {
$,
// Using a getter here not to break the original API
// and lazy load the HTML only when needed.
get html() {
log.deprecated('The "html" parameter of handlePageFunction is deprecated, use "body" instead.');
return dom && !isXml && $.html({ decodeEntities: false });
},
get json() {
if (contentType.type !== 'application/json') return null;
const jsonString = body.toString(contentType.encoding);
return JSON.parse(jsonString);
},
get body() {
// NOTE: For XML/HTML documents, we don't store the original body and only reconstruct it from Cheerio's DOM.
// This is to save memory for high-concurrency crawls. The downside is that changes
// made to DOM are reflected in the HTML, but we can live with that...
if (dom) {
return isXml ? $.xml() : $.html({ decodeEntities: false });
}
return body;
},
contentType,
request,
response,
autoscaledPool,
session,
proxyInfo,
};
return addTimeoutToPromise(
this.handlePageFunction(context),
this.handlePageTimeoutMillis,
`handlePageFunction timed out after ${this.handlePageTimeoutMillis / 1000} seconds.`,
);
}
/**
* Function to make the HTTP request. It performs optimizations
* on the request such as only downloading the request body if the
* received content type matches text/html, application/xml, application/xhtml+xml.
*
* @param {Object} options
* @param {Request} options.request
* @param {Session} options.session
* @param {string} options.proxyUrl
* @ignore
*/
async _requestFunction({ request, session, proxyUrl }) {
// Using the streaming API of Request to be able to
// handle the response based on headers receieved.
if (this.persistCookiesPerSession) {
const { headers } = request;
headers.Cookie = session.getCookieString(request.url);
}
const opts = this._getRequestOptions(request, session, proxyUrl);
let responseStream;
try {
responseStream = await utilsRequest.requestAsBrowser(opts);
} catch (e) {
if (e instanceof TimeoutError) {
this._handleRequestTimeout(session);
} else {
throw e;
}
}
const { statusCode } = responseStream;
const { type, charset } = parseContentTypeFromResponse(responseStream);
const { response, encoding } = this._encodeResponse(request, responseStream, charset);
const contentType = { type, encoding };
if (statusCode >= 500) {
const body = await readStreamToString(response, encoding);
// Errors are often sent as JSON, so attempt to parse them,
// despite Accept header being set to text/html.
if (type === 'application/json') {
const errorResponse = JSON.parse(body);
let { message } = errorResponse;
if (!message) message = util.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });
throw new Error(`${statusCode} - ${message}`);
}
// It's not a JSON so it's probably some text. Get the first 100 chars of it.
throw new Error(`${statusCode} - Internal Server Error: ${body.substr(0, 100)}`);
} else if (type === 'text/html' || type === 'application/xhtml+xml' || type === 'application/xml') {
const dom = await this._parseHtmlToDom(response);
return ({ dom, isXml: type.includes('xml'), response, contentType });
} else {
const body = await concatStreamToBuffer(response);
return { body, response, contentType };
}
}
/**
* Combines the provided `requestOptions` with mandatory (non-overridable) values.
* @param {Request} request
* @param {Session} [session]
* @param {string} [proxyUrl]
* @ignore
*/
_getRequestOptions(request, session, proxyUrl) {
const mandatoryRequestOptions = {
url: request.url,
method: request.method,
headers: Object.assign({}, request.headers),
ignoreSslErrors: this.ignoreSslErrors,
proxyUrl,
stream: true,
useCaseSensitiveHeaders: true,
abortFunction: (res) => {
const { statusCode } = res;
const { type } = parseContentTypeFromResponse(res);
if (statusCode === 406) {
request.noRetry = true;
throw new Error(`Resource ${request.url} is not available in HTML format. Skipping resource.`);
}
if (!this.supportedMimeTypes.has(type) && statusCode < 500) {
request.noRetry = true;
throw new Error(`Resource ${request.url} served Content-Type ${type}, `
+ `but only ${Array.from(this.supportedMimeTypes).join(', ')} are allowed. Skipping resource.`);
}
return false;
},
timeoutSecs: this.requestTimeoutMillis / 1000,
};
if (/PATCH|POST|PUT/.test(request.method)) mandatoryRequestOptions.payload = request.payload;
return Object.assign({}, this.requestOptions, mandatoryRequestOptions);
}
_encodeResponse(request, response, encoding) {
if (this.forceResponseEncoding) {
encoding = this.forceResponseEncoding;
} else if (!encoding && this.suggestResponseEncoding) {
encoding = this.suggestResponseEncoding;
}
// Fall back to utf-8 if we still don't have encoding.
const utf8 = 'utf8';
if (!encoding) return { response, encoding: utf8 };
// This means that the encoding is one of Node.js supported
// encodings and we don't need to re-encode it.
if (Buffer.isEncoding(encoding)) return { response, encoding };
// Try to re-encode a variety of unsupported encodings to utf-8
if (iconv.encodingExists(encoding)) {
const encodeStream = iconv.encodeStream(utf8);
const decodeStream = iconv.decodeStream(encoding).on('error', err => encodeStream.emit('error', err));
response.on('error', err => decodeStream.emit('error', err));
const encodedResponse = response.pipe(decodeStream).pipe(encodeStream);
encodedResponse.statusCode = response.statusCode;
encodedResponse.headers = response.headers;
encodedResponse.url = response.url;
return {
response: encodedResponse,
encoding: utf8,
};
}
throw new Error(`Resource ${request.url} served with unsupported charset/encoding: ${encoding}`);
}
async _parseHtmlToDom(response) {
return new Promise((resolve, reject) => {
const domHandler = new htmlparser.DomHandler((err, dom) => {
if (err) reject(err);
else resolve(dom);
});
const parser = new htmlparser.WritableStream(domHandler, { decodeEntities: true });
response.on('error', reject).pipe(parser);
});
}
/**
* Checks and extends supported mime types
* @param {Array<(string|Object)>} additionalMimeTypes
* @ignore
*/
_extendSupportedMimeTypes(additionalMimeTypes) {
additionalMimeTypes.forEach((mimeType) => {
try {
const parsedType = contentTypeParser.parse(mimeType);
this.supportedMimeTypes.add(parsedType.type);
} catch (err) {
throw new Error(`Can not parse mime type ${mimeType} from "options.additionalMimeTypes".`);
}
});
}
/**
* Handles blocked request
* @param {Session} session
* @param {number} statusCode
* @private
*/
_throwOnBlockedRequest(session, statusCode) {
const isBlocked = session.retireOnBlockedStatusCodes(statusCode);
if (isBlocked) {
throw new Error(`Request blocked - received ${statusCode} status code`);
}
}
/**
* Handles timeout request
* @param {Session} session
* @private
*/
_handleRequestTimeout(session) {
if (session) session.markBad();
throw new Error(`request timed out after ${this.handlePageTimeoutMillis / 1000} seconds.`);
}
/**
* @param {Object} options
* @param {Error} options.error
* @param {Request} options.request
* @return {Promise<void>}
* @ignore
*/
async _defaultHandleFailedRequestFunction({ error, request }) { // eslint-disable-line class-methods-use-this
const details = _.pick(request, 'id', 'url', 'method', 'uniqueKey');
this.log.exception(error, 'Request failed and reached maximum retries', details);
}
} |
JavaScript | class CLRP {
// array of clrp inputs
clrps = [];
constructor() {
this.init();
this.addStyles();
}
init() {
var inputs = document.getElementsByClassName("clrp");
// convert each input to a clrp input
this.clrps = [...inputs].map((i) => new CLRPInput(i));
}
// add default styles to page head
addStyles() {
var style = document.createElement("style");
style.id = "clrp-style"
var rules = `
.clrp {
--color-value: #ff0000;
background-color: var(--color-value);
color: var(--color-value);
cursor: pointer;
height: 2em;
width: 2em;
padding: 0;
}
.clrp:focus {
outline: none;
}
.clrp-window {
width: 10em;
height: auto;
padding: 0.5em;
position: absolute;
display: inline-block;
text-align: center;
background-color: #f4f4f5;
border: solid 1px black;
border-radius: 3px;
box-shadow: 1px 1px 1px;
z-index: 1;
}
.clrp-window input {
box-sizing: border-box;
width: 100%;
margin: 0;
}
.clrp-window > .clrp-current {
width: auto;
height: 8em;
border: solid 1px black;
background-color: hsl(var(--clrp-hue), var(--clrp-sat), var(--clrp-light));
}
.clrp-window input[type="range"]::-moz-range-track {
height: 1.5em;
border: solid 1px black;
}
.clrp-window input[type="range"]::-webkit-slider-runnable-track {
height: 1.5em;
border: solid 1px black;
}
.clrp-hue-slider::-moz-range-track {
background: linear-gradient(to right,
hsl(0, 100%, 50%), hsl(60, 100%, 50%),
hsl(120, 100%, 50%), hsl(180, 100%, 50%),
hsl(240, 100%, 50%), hsl(300, 100%, 50%),
hsl(360, 100%, 50%));
}
.clrp-hue-slider::-webkit-slider-runnable-track {
background: linear-gradient(to right,
hsl(0, 100%, 50%), hsl(60, 100%, 50%),
hsl(120, 100%, 50%), hsl(180, 100%, 50%),
hsl(240, 100%, 50%), hsl(300, 100%, 50%),
hsl(360, 100%, 50%));
}
.clrp-sat-slider::-moz-range-track {
background: linear-gradient(to right,
hsl(0, 0%, 50%), hsl(var(--clrp-hue), 100%, var(--clrp-light)));
}
.clrp-sat-slider::-webkit-slider-runnable-track {
background: linear-gradient(to right,
hsl(0, 0%, 50%), hsl(var(--clrp-hue), 100%, var(--clrp-light)));
}
.clrp-light-slider::-moz-range-track {
background: linear-gradient(to right,
hsl(var(--clrp-hue), var(--clrp-sat), 0%),
hsl(var(--clrp-hue), var(--clrp-sat), 50%),
hsl(var(--clrp-hue), var(--clrp-sat), 100%));
}
.clrp-light-slider::-webkit-slider-runnable-track {
background: linear-gradient(to right,
hsl(var(--clrp-hue), var(--clrp-sat), 0%),
hsl(var(--clrp-hue), var(--clrp-sat), 50%),
hsl(var(--clrp-hue), var(--clrp-sat), 100%));
}
`;
style.innerHTML = rules;
document.head.appendChild(style);
}
} |
JavaScript | class Verifier {
static get domainsBasePath() {
return path.resolve(__dirname, './domains');
}
/**
* check's if the email address is valid (in an proper email format - RFC 2822)
* @param {string} emailAddress email address to be checked
* @returns {boolean} true, if the email address is valid, false, otherwise
*/
static isValidEmailAddress(emailAddress) {
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(emailAddress).toLowerCase());
}
/**
* converts tld to url format
* @param {string} emailAddress email address to be converted
* @returns {string} tld as url
*/
static domainToUrl(domain) {
let domainUrl = domain.split('.');
domainUrl[0] = domainUrl[0] + '.txt';
domainUrl = domainUrl.reverse().join('/');
return domainUrl;
}
/**
* check's if the email address is academic
* @param {string} emailAddress email address to be checked
* @returns {Promise<boolean>} true, if the email address is academic, false, otherwise
*/
static isAcademic(emailAddress) {
return new Promise((resolve, reject) => {
if (!this.isValidEmailAddress(emailAddress)) {
reject(Error("Email address is not properly formatted"));
} else {
let domain = emailAddress.split("@").reverse()[0];
let domainUrl = this.domainToUrl(domain);
let domainPath = path.join(this.domainsBasePath, domainUrl);
// check if the domain is blacklisted
if (blacklist.indexOf(domain) === -1) {
// check if the domain file exist
fs.access(domainPath, fs.constants.F_OK, (error) => {
if (error) {
resolve(false);
} else {
resolve(true);
}
});
} else {
resolve(false);
}
}
});
}
/**
* query email address institution name
* @param {string} emailAddress email address to be checked
* @returns {Promise<string>} academic institution name, if exist, '', otherwise
*/
static getInstitutionName(emailAddress) {
return new Promise((resolve, reject) => {
if (!this.isValidEmailAddress(emailAddress)) {
reject(Error("Email address is not properly formatted"));
} else {
let domain = emailAddress.split("@").reverse()[0];
let domainUrl = this.domainToUrl(domain);
let domainPath = path.join(this.domainsBasePath, domainUrl);
// check if the domain is blacklisted
if (blacklist.indexOf(domain) === -1) {
fs.access(domainPath, fs.constants.R_OK, (error) => {
if (error) {
resolve('');
} else {
// try to read the domain institution name
fs.readFile(domainPath, (error, data) => {
if (error) {
console.error('[Academic Email Verifier]', error);
reject('');
} else {
resolve(data.toString('utf8'));
}
});
}
});
} else {
resolve('');
}
}
});
}
} |
JavaScript | class AnsweredPollStats extends Component {
render() {
const { id, poll, currentUser } = this.props;
const answer = Object.assign({}, ...currentUser.answers)[id];
const optionOneVotes = { raw: poll.optionOne.votes.length };
const optionTwoVotes = { raw: poll.optionTwo.votes.length };
const total = optionOneVotes.raw + optionTwoVotes.raw;
optionOneVotes.percent = (optionOneVotes.raw / total) * 100;
optionOneVotes.voters = poll.optionOne.votes;
optionTwoVotes.percent = (optionTwoVotes.raw / total) * 100;
optionTwoVotes.voters = poll.optionOne.votes;
return (
<CardContent>
<Box>
<Box
p="0.5rem"
border={answer === "optionOne" ? 2 : 0}
borderColor="primary.main"
borderRadius="10px"
>
<Typography
variant={answer === "optionOne" ? "h6" : "body2"}
color={answer === "optionOne" ? "primary" : "initial"}
>{`${poll.optionOne.text}:`}</Typography>
{LinearProgressWithLabel(
optionOneVotes,
answer === "optionOne" ? "primary" : "secondary"
)}
</Box>
<Box
p="0.5rem"
border={answer === "optionTwo" ? 2 : 0}
borderColor="primary.main"
borderRadius="10px"
>
<Typography
variant={answer === "optionTwo" ? "h6" : "body2"}
color={answer === "optionTwo" ? "primary" : "initial"}
>{`${poll.optionTwo.text}:`}</Typography>
{LinearProgressWithLabel(
optionTwoVotes,
answer === "optionTwo" ? "primary" : "secondary"
)}
</Box>
</Box>
</CardContent>
);
}
} |
JavaScript | class InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare {
/**
* Constructs a new <code>InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare</code>.
* Per-share figures.
* @alias module:model/InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare
*/
constructor() {
InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare} obj Optional instance to populate.
* @return {module:model/InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare} The populated <code>InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShare();
if (data.hasOwnProperty('sales')) {
obj['sales'] = InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShareSales.constructFromObject(data['sales']);
}
if (data.hasOwnProperty('earnings')) {
obj['earnings'] = InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShareEarnings.constructFromObject(data['earnings']);
}
if (data.hasOwnProperty('dividends')) {
obj['dividends'] = InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShareDividends.constructFromObject(data['dividends']);
}
if (data.hasOwnProperty('cashFlow')) {
obj['cashFlow'] = InlineResponse2004EstimatesFirstFiscalYearCurrencyDependentEstimatesPerShareCashFlow.constructFromObject(data['cashFlow']);
}
}
return obj;
}
} |
JavaScript | class HeaderManager {
/**
* The class constructor.
*/
constructor() {
// This class is meant to be extended by other classes, then it cannot be instantiated directly.
if ( new.target === 'HeaderManager' ){
throw new RuntimeException('Cannot instance a class that is meant to be abstract.', 1);
}
}
/**
* Generates the HTTP headers to include in the client response.
*
* @param {module:http.IncomingMessage} request An instance of the built-in class "IncomingMessage" containing all the connection properties.
* @param {module:http.ServerResponse} response An instance of the built-in class "ServerResponse" representing the response that will be sent back to the client.
*
* @returns {Object.<string, (string|string[])>} An object having as key the header name and as value one or multiple values (represented as an array).
*
* @throws {NotCallableException} If this method is called without been overridden and implemented.
*
* @abstract
*/
buildHeaders(request, response){
throw new NotCallableException('This method cannot be callable, you must extend this class and override this method.', 1);
}
} |
JavaScript | class JSONSchemaTemplateError extends Error {
/**
* @param {*} args Error message
*/
constructor(...args) {
super(...args);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
} |
Subsets and Splits