id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
21,800 | waterlock/waterlock | lib/validator.js | function(token, address, cb){
waterlock.Jwt.findOne({token: token}, function(err, j){
if(err){
return cb(err);
}
if(!j){
waterlock.logger.debug('access token not found');
return cb('Token not found');
}
if(j.revoked){
waterlock.logger.debug('access token rejected, reason: REVOKED');
return cb('This token has been revoked');
}
var use = {jsonWebToken: j.id, remoteAddress: address.ip};
waterlock.Use.create(use).exec(function(){});
cb(null);
});
} | javascript | function(token, address, cb){
waterlock.Jwt.findOne({token: token}, function(err, j){
if(err){
return cb(err);
}
if(!j){
waterlock.logger.debug('access token not found');
return cb('Token not found');
}
if(j.revoked){
waterlock.logger.debug('access token rejected, reason: REVOKED');
return cb('This token has been revoked');
}
var use = {jsonWebToken: j.id, remoteAddress: address.ip};
waterlock.Use.create(use).exec(function(){});
cb(null);
});
} | [
"function",
"(",
"token",
",",
"address",
",",
"cb",
")",
"{",
"waterlock",
".",
"Jwt",
".",
"findOne",
"(",
"{",
"token",
":",
"token",
"}",
",",
"function",
"(",
"err",
",",
"j",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"!",
"j",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'access token not found'",
")",
";",
"return",
"cb",
"(",
"'Token not found'",
")",
";",
"}",
"if",
"(",
"j",
".",
"revoked",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'access token rejected, reason: REVOKED'",
")",
";",
"return",
"cb",
"(",
"'This token has been revoked'",
")",
";",
"}",
"var",
"use",
"=",
"{",
"jsonWebToken",
":",
"j",
".",
"id",
",",
"remoteAddress",
":",
"address",
".",
"ip",
"}",
";",
"waterlock",
".",
"Use",
".",
"create",
"(",
"use",
")",
".",
"exec",
"(",
"function",
"(",
")",
"{",
"}",
")",
";",
"cb",
"(",
"null",
")",
";",
"}",
")",
";",
"}"
] | Finds the DAO instance of the give token and tracks the usage
@param {String} token the raw token
@param {Object} address the transport address
@param {Function} cb Callback to be invoked when an error has
occured or the token was tracked successfully | [
"Finds",
"the",
"DAO",
"instance",
"of",
"the",
"give",
"token",
"and",
"tracks",
"the",
"usage"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/validator.js#L133-L154 | |
21,801 | waterlock/waterlock | lib/validator.js | function(address, token, user, cb){
this.findAndTrackJWT(token, address, function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
cb(null, user);
});
} | javascript | function(address, token, user, cb){
this.findAndTrackJWT(token, address, function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
cb(null, user);
});
} | [
"function",
"(",
"address",
",",
"token",
",",
"user",
",",
"cb",
")",
"{",
"this",
".",
"findAndTrackJWT",
"(",
"token",
",",
"address",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"cb",
"(",
"null",
",",
"user",
")",
";",
"}",
")",
";",
"}"
] | Tracks the tokens usage and invokes the user defined callback
@param {Object} address the transport address
@param {String} token the raw token
@param {Waterline DAO} user the waterline user object
@param {Function} cb Callback to be invoked when an error has occured
or the token has been tracked successfully | [
"Tracks",
"the",
"tokens",
"usage",
"and",
"invokes",
"the",
"user",
"defined",
"callback"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/validator.js#L165-L173 | |
21,802 | waterlock/waterlock | lib/waterlock.js | Waterlock | function Waterlock(){
events.EventEmitter.call(this);
this.sails = global.sails;
this.engine = _.bind(this.engine, this)();
this.config = _.bind(this.config, this)();
this.methods = _.bind(this.methods, this)().collect();
this.models = _.bind(this.models, this)();
this.actions = _.bind(this.actions, this)();
this.cycle = _.bind(this.cycle, this)();
// expose jwt so the implementing
// app doesn't need to require it.
this.jwt = require('jwt-simple');
this.validator = _.bind(this.validator, this)();
} | javascript | function Waterlock(){
events.EventEmitter.call(this);
this.sails = global.sails;
this.engine = _.bind(this.engine, this)();
this.config = _.bind(this.config, this)();
this.methods = _.bind(this.methods, this)().collect();
this.models = _.bind(this.models, this)();
this.actions = _.bind(this.actions, this)();
this.cycle = _.bind(this.cycle, this)();
// expose jwt so the implementing
// app doesn't need to require it.
this.jwt = require('jwt-simple');
this.validator = _.bind(this.validator, this)();
} | [
"function",
"Waterlock",
"(",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"sails",
"=",
"global",
".",
"sails",
";",
"this",
".",
"engine",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"engine",
",",
"this",
")",
"(",
")",
";",
"this",
".",
"config",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"config",
",",
"this",
")",
"(",
")",
";",
"this",
".",
"methods",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"methods",
",",
"this",
")",
"(",
")",
".",
"collect",
"(",
")",
";",
"this",
".",
"models",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"models",
",",
"this",
")",
"(",
")",
";",
"this",
".",
"actions",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"actions",
",",
"this",
")",
"(",
")",
";",
"this",
".",
"cycle",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"cycle",
",",
"this",
")",
"(",
")",
";",
"// expose jwt so the implementing ",
"// app doesn't need to require it.",
"this",
".",
"jwt",
"=",
"require",
"(",
"'jwt-simple'",
")",
";",
"this",
".",
"validator",
"=",
"_",
".",
"bind",
"(",
"this",
".",
"validator",
",",
"this",
")",
"(",
")",
";",
"}"
] | Creates a waterlock instance | [
"Creates",
"a",
"waterlock",
"instance"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/waterlock.js#L12-L29 |
21,803 | waterlock/waterlock | lib/engine.js | function(auth, cb){
var self = this;
// create the user
if(!auth.user){
waterlock.User.create({auth:auth.id}).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// update the auth object
waterlock.Auth.update(auth.id, {user:user.id}).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth.shift();
cb(err, user);
});
});
}else{
// just fire off update to user object so we can get the
// backwards association going.
if(!auth.user.auth){
waterlock.User.update(auth.user.id, {auth:auth.id}).exec(function(){});
}
cb(null, self._invertAuth(auth));
}
} | javascript | function(auth, cb){
var self = this;
// create the user
if(!auth.user){
waterlock.User.create({auth:auth.id}).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// update the auth object
waterlock.Auth.update(auth.id, {user:user.id}).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth.shift();
cb(err, user);
});
});
}else{
// just fire off update to user object so we can get the
// backwards association going.
if(!auth.user.auth){
waterlock.User.update(auth.user.id, {auth:auth.id}).exec(function(){});
}
cb(null, self._invertAuth(auth));
}
} | [
"function",
"(",
"auth",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// create the user",
"if",
"(",
"!",
"auth",
".",
"user",
")",
"{",
"waterlock",
".",
"User",
".",
"create",
"(",
"{",
"auth",
":",
"auth",
".",
"id",
"}",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"// update the auth object",
"waterlock",
".",
"Auth",
".",
"update",
"(",
"auth",
".",
"id",
",",
"{",
"user",
":",
"user",
".",
"id",
"}",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"auth",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"user",
".",
"auth",
"=",
"auth",
".",
"shift",
"(",
")",
";",
"cb",
"(",
"err",
",",
"user",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// just fire off update to user object so we can get the",
"// backwards association going.",
"if",
"(",
"!",
"auth",
".",
"user",
".",
"auth",
")",
"{",
"waterlock",
".",
"User",
".",
"update",
"(",
"auth",
".",
"user",
".",
"id",
",",
"{",
"auth",
":",
"auth",
".",
"id",
"}",
")",
".",
"exec",
"(",
"function",
"(",
")",
"{",
"}",
")",
";",
"}",
"cb",
"(",
"null",
",",
"self",
".",
"_invertAuth",
"(",
"auth",
")",
")",
";",
"}",
"}"
] | This will create a user and auth object if one is not found
@param {Object} criteria should be id to find the auth by
@param {Object} attributes auth attributes
@param {Function} cb function to be called when the auth has been
found or an error has occurred
@api private | [
"This",
"will",
"create",
"a",
"user",
"and",
"auth",
"object",
"if",
"one",
"is",
"not",
"found"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/engine.js#L41-L72 | |
21,804 | waterlock/waterlock | lib/engine.js | function(criteria, attributes, cb){
var self = this;
waterlock.Auth.findOrCreate(criteria, attributes)
.exec(function(err, newAuth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
waterlock.Auth.findOne(newAuth.id).populate('user')
.exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
self._attachAuthToUser(auth, cb);
});
});
} | javascript | function(criteria, attributes, cb){
var self = this;
waterlock.Auth.findOrCreate(criteria, attributes)
.exec(function(err, newAuth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
waterlock.Auth.findOne(newAuth.id).populate('user')
.exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
self._attachAuthToUser(auth, cb);
});
});
} | [
"function",
"(",
"criteria",
",",
"attributes",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"waterlock",
".",
"Auth",
".",
"findOrCreate",
"(",
"criteria",
",",
"attributes",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"newAuth",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"waterlock",
".",
"Auth",
".",
"findOne",
"(",
"newAuth",
".",
"id",
")",
".",
"populate",
"(",
"'user'",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"auth",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"self",
".",
"_attachAuthToUser",
"(",
"auth",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Find or create the auth then pass the results to _attachAuthToUser
@param {Object} criteria should be id to find the auth by
@param {Object} attributes auth attributes
@param {Function} cb function to be called when the auth has been
found or an error has occurred
@api public | [
"Find",
"or",
"create",
"the",
"auth",
"then",
"pass",
"the",
"results",
"to",
"_attachAuthToUser"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/engine.js#L84-L103 | |
21,805 | waterlock/waterlock | lib/engine.js | function(attributes, user, cb){
var self = this;
attributes.user = user.id;
waterlock.User.findOne(user.id).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
if(user.auth){
delete(attributes.auth);
//update existing auth
waterlock.Auth.findOne(user.auth).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// Check if any attribtues have changed if so update them
if(self._updateAuth(auth, attributes)){
auth.save(function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth;
cb(err, user);
});
}else{
user.auth = auth;
cb(err, user);
}
});
}else{
// force create by pass of user id
self.findOrCreateAuth(user.id, attributes, cb);
}
});
} | javascript | function(attributes, user, cb){
var self = this;
attributes.user = user.id;
waterlock.User.findOne(user.id).exec(function(err, user){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
if(user.auth){
delete(attributes.auth);
//update existing auth
waterlock.Auth.findOne(user.auth).exec(function(err, auth){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
// Check if any attribtues have changed if so update them
if(self._updateAuth(auth, attributes)){
auth.save(function(err){
if(err){
waterlock.logger.debug(err);
return cb(err);
}
user.auth = auth;
cb(err, user);
});
}else{
user.auth = auth;
cb(err, user);
}
});
}else{
// force create by pass of user id
self.findOrCreateAuth(user.id, attributes, cb);
}
});
} | [
"function",
"(",
"attributes",
",",
"user",
",",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
";",
"attributes",
".",
"user",
"=",
"user",
".",
"id",
";",
"waterlock",
".",
"User",
".",
"findOne",
"(",
"user",
".",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"if",
"(",
"user",
".",
"auth",
")",
"{",
"delete",
"(",
"attributes",
".",
"auth",
")",
";",
"//update existing auth",
"waterlock",
".",
"Auth",
".",
"findOne",
"(",
"user",
".",
"auth",
")",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"auth",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"// Check if any attribtues have changed if so update them",
"if",
"(",
"self",
".",
"_updateAuth",
"(",
"auth",
",",
"attributes",
")",
")",
"{",
"auth",
".",
"save",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"user",
".",
"auth",
"=",
"auth",
";",
"cb",
"(",
"err",
",",
"user",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"user",
".",
"auth",
"=",
"auth",
";",
"cb",
"(",
"err",
",",
"user",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// force create by pass of user id",
"self",
".",
"findOrCreateAuth",
"(",
"user",
".",
"id",
",",
"attributes",
",",
"cb",
")",
";",
"}",
"}",
")",
";",
"}"
] | Attach given auth attributes to user
@param {Object} attributes auth attributes
@param {Object} user user instance
@param {Function} cb function to be called when the auth has been
attached or an error has occurred
@api public | [
"Attach",
"given",
"auth",
"attributes",
"to",
"user"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/engine.js#L114-L154 | |
21,806 | waterlock/waterlock | lib/engine.js | function(auth){
// nothing to invert
if(!auth || !auth.user){
return auth;
}
var u = auth.user;
delete(auth.user);
u.auth = auth;
return u;
} | javascript | function(auth){
// nothing to invert
if(!auth || !auth.user){
return auth;
}
var u = auth.user;
delete(auth.user);
u.auth = auth;
return u;
} | [
"function",
"(",
"auth",
")",
"{",
"// nothing to invert",
"if",
"(",
"!",
"auth",
"||",
"!",
"auth",
".",
"user",
")",
"{",
"return",
"auth",
";",
"}",
"var",
"u",
"=",
"auth",
".",
"user",
";",
"delete",
"(",
"auth",
".",
"user",
")",
";",
"u",
".",
"auth",
"=",
"auth",
";",
"return",
"u",
";",
"}"
] | Inverts the auth object so we don't need to run another query
@param {Object} auth Auth object
@return {Object} User object
@api private | [
"Inverts",
"the",
"auth",
"object",
"so",
"we",
"don",
"t",
"need",
"to",
"run",
"another",
"query"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/engine.js#L163-L173 | |
21,807 | waterlock/waterlock | lib/engine.js | function(auth, attributes){
if(!_.isEqual(auth, attributes)){
_.merge(auth, attributes);
return true;
}
return false;
} | javascript | function(auth, attributes){
if(!_.isEqual(auth, attributes)){
_.merge(auth, attributes);
return true;
}
return false;
} | [
"function",
"(",
"auth",
",",
"attributes",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isEqual",
"(",
"auth",
",",
"attributes",
")",
")",
"{",
"_",
".",
"merge",
"(",
"auth",
",",
"attributes",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Decorates the auth object with values of the attributes object
where the attributes differ from the auth
@param {Object} auth waterline Auth instance
@param {Object} attributes used to update auth with
@return {Boolean} true if any values were updated | [
"Decorates",
"the",
"auth",
"object",
"with",
"values",
"of",
"the",
"attributes",
"object",
"where",
"the",
"attributes",
"differ",
"from",
"the",
"auth"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/engine.js#L183-L189 | |
21,808 | waterlock/waterlock | lib/controllers/index.js | function(actions){
waterlock.logger.verbose('bootstraping user actions');
var template = {
jwt: require('./actions/jwt')
};
return _.merge(template, actions);
} | javascript | function(actions){
waterlock.logger.verbose('bootstraping user actions');
var template = {
jwt: require('./actions/jwt')
};
return _.merge(template, actions);
} | [
"function",
"(",
"actions",
")",
"{",
"waterlock",
".",
"logger",
".",
"verbose",
"(",
"'bootstraping user actions'",
")",
";",
"var",
"template",
"=",
"{",
"jwt",
":",
"require",
"(",
"'./actions/jwt'",
")",
"}",
";",
"return",
"_",
".",
"merge",
"(",
"template",
",",
"actions",
")",
";",
"}"
] | bootstraps user defined overrides with template actions
@param {object} actions user defiend actions
@return {object} user actions merged with template | [
"bootstraps",
"user",
"defined",
"overrides",
"with",
"template",
"actions"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/controllers/index.js#L46-L53 | |
21,809 | waterlock/waterlock | lib/cycle.js | function(req, res, user) {
waterlock.logger.debug('user registration success');
if (!user) {
waterlock.logger.debug('registerSuccess requires a valid user object');
return res.serverError();
}
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: true
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
// store user in && authenticate the session
req.session.user = user;
req.session.authenticated = true;
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.success, user);
if (postResponse === 'jwt') {
//Returns the token immediately
var jwtData = waterlock._utils.createJwt(req, res, user);
Jwt.create({token: jwtData.token, uses: 0, owner: user.id}).exec(function(err){
if(err){
return res.serverError('JSON web token could not be created');
}
var result = {};
result[waterlock.config.jsonWebTokens.tokenProperty] = jwtData.token;
result[waterlock.config.jsonWebTokens.expiresProperty] = jwtData.expires;
if (waterlock.config.jsonWebTokens.includeUserInJwtResponse) {
result['user'] = user;
}
res.json(result);
});
}else if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | javascript | function(req, res, user) {
waterlock.logger.debug('user registration success');
if (!user) {
waterlock.logger.debug('registerSuccess requires a valid user object');
return res.serverError();
}
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: true
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
// store user in && authenticate the session
req.session.user = user;
req.session.authenticated = true;
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.success, user);
if (postResponse === 'jwt') {
//Returns the token immediately
var jwtData = waterlock._utils.createJwt(req, res, user);
Jwt.create({token: jwtData.token, uses: 0, owner: user.id}).exec(function(err){
if(err){
return res.serverError('JSON web token could not be created');
}
var result = {};
result[waterlock.config.jsonWebTokens.tokenProperty] = jwtData.token;
result[waterlock.config.jsonWebTokens.expiresProperty] = jwtData.expires;
if (waterlock.config.jsonWebTokens.includeUserInJwtResponse) {
result['user'] = user;
}
res.json(result);
});
}else if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | [
"function",
"(",
"req",
",",
"res",
",",
"user",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'user registration success'",
")",
";",
"if",
"(",
"!",
"user",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'registerSuccess requires a valid user object'",
")",
";",
"return",
"res",
".",
"serverError",
"(",
")",
";",
"}",
"var",
"address",
"=",
"this",
".",
"_addressFromRequest",
"(",
"req",
")",
";",
"var",
"attempt",
"=",
"{",
"user",
":",
"user",
".",
"id",
",",
"successful",
":",
"true",
"}",
";",
"_",
".",
"merge",
"(",
"attempt",
",",
"address",
")",
";",
"waterlock",
".",
"Attempt",
".",
"create",
"(",
"attempt",
")",
".",
"exec",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"// store user in && authenticate the session",
"req",
".",
"session",
".",
"user",
"=",
"user",
";",
"req",
".",
"session",
".",
"authenticated",
"=",
"true",
";",
"// now respond or redirect",
"var",
"postResponse",
"=",
"this",
".",
"_resolvePostAction",
"(",
"waterlock",
".",
"config",
".",
"postActions",
".",
"register",
".",
"success",
",",
"user",
")",
";",
"if",
"(",
"postResponse",
"===",
"'jwt'",
")",
"{",
"//Returns the token immediately",
"var",
"jwtData",
"=",
"waterlock",
".",
"_utils",
".",
"createJwt",
"(",
"req",
",",
"res",
",",
"user",
")",
";",
"Jwt",
".",
"create",
"(",
"{",
"token",
":",
"jwtData",
".",
"token",
",",
"uses",
":",
"0",
",",
"owner",
":",
"user",
".",
"id",
"}",
")",
".",
"exec",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"res",
".",
"serverError",
"(",
"'JSON web token could not be created'",
")",
";",
"}",
"var",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"waterlock",
".",
"config",
".",
"jsonWebTokens",
".",
"tokenProperty",
"]",
"=",
"jwtData",
".",
"token",
";",
"result",
"[",
"waterlock",
".",
"config",
".",
"jsonWebTokens",
".",
"expiresProperty",
"]",
"=",
"jwtData",
".",
"expires",
";",
"if",
"(",
"waterlock",
".",
"config",
".",
"jsonWebTokens",
".",
"includeUserInJwtResponse",
")",
"{",
"result",
"[",
"'user'",
"]",
"=",
"user",
";",
"}",
"res",
".",
"json",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"postResponse",
"===",
"'string'",
"&&",
"this",
".",
"_isURI",
"(",
"postResponse",
")",
")",
"{",
"res",
".",
"redirect",
"(",
"postResponse",
")",
";",
"}",
"else",
"{",
"res",
".",
"ok",
"(",
"postResponse",
")",
";",
"}",
"}"
] | handles successful logins
@param {Object} req express request object
@param {Object} res expresss response object
@param {Object} user the user instance
@api public | [
"handles",
"successful",
"logins"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L23-L77 | |
21,810 | waterlock/waterlock | lib/cycle.js | function(req, res, user, error) {
waterlock.logger.debug('user register failure');
if (user) {
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: false
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
}
if (req.session.authenticated) {
req.session.authenticated = false;
}
delete(req.session.user);
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.failure,
error);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.forbidden(postResponse);
}
} | javascript | function(req, res, user, error) {
waterlock.logger.debug('user register failure');
if (user) {
var address = this._addressFromRequest(req);
var attempt = {
user: user.id,
successful: false
};
_.merge(attempt, address);
waterlock.Attempt.create(attempt).exec(function(err) {
if (err) {
waterlock.logger.debug(err);
}
});
}
if (req.session.authenticated) {
req.session.authenticated = false;
}
delete(req.session.user);
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.register.failure,
error);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.forbidden(postResponse);
}
} | [
"function",
"(",
"req",
",",
"res",
",",
"user",
",",
"error",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'user register failure'",
")",
";",
"if",
"(",
"user",
")",
"{",
"var",
"address",
"=",
"this",
".",
"_addressFromRequest",
"(",
"req",
")",
";",
"var",
"attempt",
"=",
"{",
"user",
":",
"user",
".",
"id",
",",
"successful",
":",
"false",
"}",
";",
"_",
".",
"merge",
"(",
"attempt",
",",
"address",
")",
";",
"waterlock",
".",
"Attempt",
".",
"create",
"(",
"attempt",
")",
".",
"exec",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"req",
".",
"session",
".",
"authenticated",
")",
"{",
"req",
".",
"session",
".",
"authenticated",
"=",
"false",
";",
"}",
"delete",
"(",
"req",
".",
"session",
".",
"user",
")",
";",
"// now respond or redirect",
"var",
"postResponse",
"=",
"this",
".",
"_resolvePostAction",
"(",
"waterlock",
".",
"config",
".",
"postActions",
".",
"register",
".",
"failure",
",",
"error",
")",
";",
"if",
"(",
"typeof",
"postResponse",
"===",
"'string'",
"&&",
"this",
".",
"_isURI",
"(",
"postResponse",
")",
")",
"{",
"res",
".",
"redirect",
"(",
"postResponse",
")",
";",
"}",
"else",
"{",
"res",
".",
"forbidden",
"(",
"postResponse",
")",
";",
"}",
"}"
] | handles registration failures
@param {Object} req express request object
@param {Object} res expresss response object
@param {Object} user the user instance
@param {Object|String} error the error that caused the failure
@api public | [
"handles",
"registration",
"failures"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L88-L123 | |
21,811 | waterlock/waterlock | lib/cycle.js | function(req, res) {
waterlock.logger.debug('user logout');
delete(req.session.user);
if (req.session.authenticated) {
this.logoutSuccess(req, res);
} else {
this.logoutFailure(req, res);
}
} | javascript | function(req, res) {
waterlock.logger.debug('user logout');
delete(req.session.user);
if (req.session.authenticated) {
this.logoutSuccess(req, res);
} else {
this.logoutFailure(req, res);
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"waterlock",
".",
"logger",
".",
"debug",
"(",
"'user logout'",
")",
";",
"delete",
"(",
"req",
".",
"session",
".",
"user",
")",
";",
"if",
"(",
"req",
".",
"session",
".",
"authenticated",
")",
"{",
"this",
".",
"logoutSuccess",
"(",
"req",
",",
"res",
")",
";",
"}",
"else",
"{",
"this",
".",
"logoutFailure",
"(",
"req",
",",
"res",
")",
";",
"}",
"}"
] | handles logout events
@param {Object} req express request object
@param {Object} res expresss response object
@api public | [
"handles",
"logout",
"events"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L242-L251 | |
21,812 | waterlock/waterlock | lib/cycle.js | function(req, res) {
req.session.authenticated = false;
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.success,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | javascript | function(req, res) {
req.session.authenticated = false;
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.success,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"req",
".",
"session",
".",
"authenticated",
"=",
"false",
";",
"var",
"defaultString",
"=",
"'You have successfully logged out.'",
";",
"// now respond or redirect",
"var",
"postResponse",
"=",
"this",
".",
"_resolvePostAction",
"(",
"waterlock",
".",
"config",
".",
"postActions",
".",
"logout",
".",
"success",
",",
"defaultString",
")",
";",
"if",
"(",
"typeof",
"postResponse",
"===",
"'string'",
"&&",
"this",
".",
"_isURI",
"(",
"postResponse",
")",
")",
"{",
"res",
".",
"redirect",
"(",
"postResponse",
")",
";",
"}",
"else",
"{",
"res",
".",
"ok",
"(",
"postResponse",
")",
";",
"}",
"}"
] | the logout 'success' event
@param {Object} req express request object
@param {Object} res express response object
@api public | [
"the",
"logout",
"success",
"event"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L260-L275 | |
21,813 | waterlock/waterlock | lib/cycle.js | function(req, res) {
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.failure,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | javascript | function(req, res) {
var defaultString = 'You have successfully logged out.';
// now respond or redirect
var postResponse = this._resolvePostAction(waterlock.config.postActions.logout.failure,
defaultString);
if (typeof postResponse === 'string' && this._isURI(postResponse)) {
res.redirect(postResponse);
} else {
res.ok(postResponse);
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"var",
"defaultString",
"=",
"'You have successfully logged out.'",
";",
"// now respond or redirect",
"var",
"postResponse",
"=",
"this",
".",
"_resolvePostAction",
"(",
"waterlock",
".",
"config",
".",
"postActions",
".",
"logout",
".",
"failure",
",",
"defaultString",
")",
";",
"if",
"(",
"typeof",
"postResponse",
"===",
"'string'",
"&&",
"this",
".",
"_isURI",
"(",
"postResponse",
")",
")",
"{",
"res",
".",
"redirect",
"(",
"postResponse",
")",
";",
"}",
"else",
"{",
"res",
".",
"ok",
"(",
"postResponse",
")",
";",
"}",
"}"
] | the logout 'failure' event
@param {Object} req express request object
@param {Object} res express response object
@api public | [
"the",
"logout",
"failure",
"event"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L284-L296 | |
21,814 | waterlock/waterlock | lib/cycle.js | function(req) {
if (req.connection && req.connection.remoteAddress) {
return {
ip: req.connection.remoteAddress,
port: req.connection.remotePort
};
}
if (req.socket && req.socket.remoteAddress) {
return {
ip: req.socket.remoteAddress,
port: req.socket.remotePort
};
}
return {
ip: '0.0.0.0',
port: 'n/a'
};
} | javascript | function(req) {
if (req.connection && req.connection.remoteAddress) {
return {
ip: req.connection.remoteAddress,
port: req.connection.remotePort
};
}
if (req.socket && req.socket.remoteAddress) {
return {
ip: req.socket.remoteAddress,
port: req.socket.remotePort
};
}
return {
ip: '0.0.0.0',
port: 'n/a'
};
} | [
"function",
"(",
"req",
")",
"{",
"if",
"(",
"req",
".",
"connection",
"&&",
"req",
".",
"connection",
".",
"remoteAddress",
")",
"{",
"return",
"{",
"ip",
":",
"req",
".",
"connection",
".",
"remoteAddress",
",",
"port",
":",
"req",
".",
"connection",
".",
"remotePort",
"}",
";",
"}",
"if",
"(",
"req",
".",
"socket",
"&&",
"req",
".",
"socket",
".",
"remoteAddress",
")",
"{",
"return",
"{",
"ip",
":",
"req",
".",
"socket",
".",
"remoteAddress",
",",
"port",
":",
"req",
".",
"socket",
".",
"remotePort",
"}",
";",
"}",
"return",
"{",
"ip",
":",
"'0.0.0.0'",
",",
"port",
":",
"'n/a'",
"}",
";",
"}"
] | returns an ip address and port from the express request object, or the
sails.io socket which is attached to the req object.
@param {Object} req express request
@return {Object} the transport address object
@api private | [
"returns",
"an",
"ip",
"address",
"and",
"port",
"from",
"the",
"express",
"request",
"object",
"or",
"the",
"sails",
".",
"io",
"socket",
"which",
"is",
"attached",
"to",
"the",
"req",
"object",
"."
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L323-L342 | |
21,815 | waterlock/waterlock | lib/cycle.js | function(obj) {
if (typeof obj.controller === 'undefined' || typeof obj.action === 'undefined') {
var error = new Error('You must define a controller and action to redirect to.').stack;
throw error;
}
return '/' + obj.controller + '/' + obj.action;
} | javascript | function(obj) {
if (typeof obj.controller === 'undefined' || typeof obj.action === 'undefined') {
var error = new Error('You must define a controller and action to redirect to.').stack;
throw error;
}
return '/' + obj.controller + '/' + obj.action;
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"typeof",
"obj",
".",
"controller",
"===",
"'undefined'",
"||",
"typeof",
"obj",
".",
"action",
"===",
"'undefined'",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"'You must define a controller and action to redirect to.'",
")",
".",
"stack",
";",
"throw",
"error",
";",
"}",
"return",
"'/'",
"+",
"obj",
".",
"controller",
"+",
"'/'",
"+",
"obj",
".",
"action",
";",
"}"
] | returns the relative path from an object, the object is
expected to look like the following
example:
{
controller: 'foo',
action: 'bar'
}
@param {Object} obj the redirect object
@return {String} the relative path
@api private | [
"returns",
"the",
"relative",
"path",
"from",
"an",
"object",
"the",
"object",
"is",
"expected",
"to",
"look",
"like",
"the",
"following"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/cycle.js#L380-L387 | |
21,816 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(target){
for(var i = 0; i < self.waterlockPlugins.length; i++){
var arr = this.readdirSyncComplete(self.waterlockPlugins[i] + '/' + target);
this.installArray = this.installArray.concat(arr);
}
} | javascript | function(target){
for(var i = 0; i < self.waterlockPlugins.length; i++){
var arr = this.readdirSyncComplete(self.waterlockPlugins[i] + '/' + target);
this.installArray = this.installArray.concat(arr);
}
} | [
"function",
"(",
"target",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"self",
".",
"waterlockPlugins",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"arr",
"=",
"this",
".",
"readdirSyncComplete",
"(",
"self",
".",
"waterlockPlugins",
"[",
"i",
"]",
"+",
"'/'",
"+",
"target",
")",
";",
"this",
".",
"installArray",
"=",
"this",
".",
"installArray",
".",
"concat",
"(",
"arr",
")",
";",
"}",
"}"
] | collects all targets to install from all waterlock modules
@param {String} target the resource to collect from waterlock module | [
"collects",
"all",
"targets",
"to",
"install",
"from",
"all",
"waterlock",
"modules"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L78-L83 | |
21,817 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(path){
var fullPath = [];
try{
var files = fs.readdirSync(path);
for(var i = 0; i < files.length; i++){
fullPath.push(path + '/' + files[i]);
}
return fullPath;
}catch(e){
return [];
}
} | javascript | function(path){
var fullPath = [];
try{
var files = fs.readdirSync(path);
for(var i = 0; i < files.length; i++){
fullPath.push(path + '/' + files[i]);
}
return fullPath;
}catch(e){
return [];
}
} | [
"function",
"(",
"path",
")",
"{",
"var",
"fullPath",
"=",
"[",
"]",
";",
"try",
"{",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"path",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"fullPath",
".",
"push",
"(",
"path",
"+",
"'/'",
"+",
"files",
"[",
"i",
"]",
")",
";",
"}",
"return",
"fullPath",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"[",
"]",
";",
"}",
"}"
] | reads contents of directory and returns an Array
of full path strings to the files
@param {String} path the directory path to search
@return {Array} array of fullpath strings of every file in directory | [
"reads",
"contents",
"of",
"directory",
"and",
"returns",
"an",
"Array",
"of",
"full",
"path",
"strings",
"to",
"the",
"files"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L103-L114 | |
21,818 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(){
console.log('');
this.log('Usage: generate [resource]');
this.log('Resources:');
this.log(' all generates all components', false);
this.log(' models generates all models', false);
this.log(' controllers generates all controllers', false);
this.log(' configs generates default configs', false);
this.log(' views generates default view templates', false);
this.log(' policies generates all policies');
} | javascript | function(){
console.log('');
this.log('Usage: generate [resource]');
this.log('Resources:');
this.log(' all generates all components', false);
this.log(' models generates all models', false);
this.log(' controllers generates all controllers', false);
this.log(' configs generates default configs', false);
this.log(' views generates default view templates', false);
this.log(' policies generates all policies');
} | [
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"''",
")",
";",
"this",
".",
"log",
"(",
"'Usage: generate [resource]'",
")",
";",
"this",
".",
"log",
"(",
"'Resources:'",
")",
";",
"this",
".",
"log",
"(",
"' all generates all components'",
",",
"false",
")",
";",
"this",
".",
"log",
"(",
"' models generates all models'",
",",
"false",
")",
";",
"this",
".",
"log",
"(",
"' controllers generates all controllers'",
",",
"false",
")",
";",
"this",
".",
"log",
"(",
"' configs generates default configs'",
",",
"false",
")",
";",
"this",
".",
"log",
"(",
"' views generates default view templates'",
",",
"false",
")",
";",
"this",
".",
"log",
"(",
"' policies generates all policies'",
")",
";",
"}"
] | Shows the script usage | [
"Shows",
"the",
"script",
"usage"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L127-L137 | |
21,819 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(src, dest){
if(fs.existsSync(dest)){
this.waitForResponse(src, dest);
}else{
this.copy(src, dest);
this.triggerNext();
}
} | javascript | function(src, dest){
if(fs.existsSync(dest)){
this.waitForResponse(src, dest);
}else{
this.copy(src, dest);
this.triggerNext();
}
} | [
"function",
"(",
"src",
",",
"dest",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"dest",
")",
")",
"{",
"this",
".",
"waitForResponse",
"(",
"src",
",",
"dest",
")",
";",
"}",
"else",
"{",
"this",
".",
"copy",
"(",
"src",
",",
"dest",
")",
";",
"this",
".",
"triggerNext",
"(",
")",
";",
"}",
"}"
] | tries to install the source file to the destination path, if it exsits
in the destination will trigger a prompt.
@param {String} src fullpath of source file to install
@param {String} dest fullpath of destination file to install | [
"tries",
"to",
"install",
"the",
"source",
"file",
"to",
"the",
"destination",
"path",
"if",
"it",
"exsits",
"in",
"the",
"destination",
"will",
"trigger",
"a",
"prompt",
"."
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L207-L214 | |
21,820 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(src, dest){
self.logger.info('generating '+dest);
fs.createReadStream(src).pipe(fs.createWriteStream(dest));
} | javascript | function(src, dest){
self.logger.info('generating '+dest);
fs.createReadStream(src).pipe(fs.createWriteStream(dest));
} | [
"function",
"(",
"src",
",",
"dest",
")",
"{",
"self",
".",
"logger",
".",
"info",
"(",
"'generating '",
"+",
"dest",
")",
";",
"fs",
".",
"createReadStream",
"(",
"src",
")",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"dest",
")",
")",
";",
"}"
] | copies the source to the destination
@param {String} src the source file
@param {String} dest the destination file | [
"copies",
"the",
"source",
"to",
"the",
"destination"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L222-L225 | |
21,821 | waterlock/waterlock | bin/waterlock-auth-methods.js | function(src, dest){
self.logger.warn('File at '+dest+' exists, overwrite?');
rl.question('(yN) ', function(answer){
switch(answer.toLowerCase()){
case 'y':
this.copy(src, dest);
this.triggerNext();
break;
case 'n':
this.triggerNext();
break;
default:
this.waitForResponse(src, dest);
break;
}
}.bind(this));
} | javascript | function(src, dest){
self.logger.warn('File at '+dest+' exists, overwrite?');
rl.question('(yN) ', function(answer){
switch(answer.toLowerCase()){
case 'y':
this.copy(src, dest);
this.triggerNext();
break;
case 'n':
this.triggerNext();
break;
default:
this.waitForResponse(src, dest);
break;
}
}.bind(this));
} | [
"function",
"(",
"src",
",",
"dest",
")",
"{",
"self",
".",
"logger",
".",
"warn",
"(",
"'File at '",
"+",
"dest",
"+",
"' exists, overwrite?'",
")",
";",
"rl",
".",
"question",
"(",
"'(yN) '",
",",
"function",
"(",
"answer",
")",
"{",
"switch",
"(",
"answer",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'y'",
":",
"this",
".",
"copy",
"(",
"src",
",",
"dest",
")",
";",
"this",
".",
"triggerNext",
"(",
")",
";",
"break",
";",
"case",
"'n'",
":",
"this",
".",
"triggerNext",
"(",
")",
";",
"break",
";",
"default",
":",
"this",
".",
"waitForResponse",
"(",
"src",
",",
"dest",
")",
";",
"break",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | prompts the user if we can overwrite the destination file
@param {String} src the source file
@param {String} dest the destination file | [
"prompts",
"the",
"user",
"if",
"we",
"can",
"overwrite",
"the",
"destination",
"file"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/bin/waterlock-auth-methods.js#L233-L250 | |
21,822 | waterlock/waterlock | lib/methods.js | function(){
var func;
if(typeof waterlock.config.authMethod[0] === 'object'){
func = this._handleObjects;
}else if(typeof waterlock.config.authMethod === 'object'){
func = this._handleObject;
}else{
func = this._handleName;
}
return func.apply(this, [waterlock.config.authMethod]);
} | javascript | function(){
var func;
if(typeof waterlock.config.authMethod[0] === 'object'){
func = this._handleObjects;
}else if(typeof waterlock.config.authMethod === 'object'){
func = this._handleObject;
}else{
func = this._handleName;
}
return func.apply(this, [waterlock.config.authMethod]);
} | [
"function",
"(",
")",
"{",
"var",
"func",
";",
"if",
"(",
"typeof",
"waterlock",
".",
"config",
".",
"authMethod",
"[",
"0",
"]",
"===",
"'object'",
")",
"{",
"func",
"=",
"this",
".",
"_handleObjects",
";",
"}",
"else",
"if",
"(",
"typeof",
"waterlock",
".",
"config",
".",
"authMethod",
"===",
"'object'",
")",
"{",
"func",
"=",
"this",
".",
"_handleObject",
";",
"}",
"else",
"{",
"func",
"=",
"this",
".",
"_handleName",
";",
"}",
"return",
"func",
".",
"apply",
"(",
"this",
",",
"[",
"waterlock",
".",
"config",
".",
"authMethod",
"]",
")",
";",
"}"
] | try to require the authentcation method defined in user config
@return {Object} containing all required auth methods
@api private | [
"try",
"to",
"require",
"the",
"authentcation",
"method",
"defined",
"in",
"user",
"config"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/methods.js#L22-L34 | |
21,823 | waterlock/waterlock | lib/methods.js | function(authMethods){
var _method = {};
var _methodName;
try{
_.each(authMethods, function(method){
_methodName = method.name;
method = _.merge(require('../../'+_methodName), method);
_method[method.authType] = method;
});
}catch(e){
this._errorHandler(_methodName);
}
return _method;
} | javascript | function(authMethods){
var _method = {};
var _methodName;
try{
_.each(authMethods, function(method){
_methodName = method.name;
method = _.merge(require('../../'+_methodName), method);
_method[method.authType] = method;
});
}catch(e){
this._errorHandler(_methodName);
}
return _method;
} | [
"function",
"(",
"authMethods",
")",
"{",
"var",
"_method",
"=",
"{",
"}",
";",
"var",
"_methodName",
";",
"try",
"{",
"_",
".",
"each",
"(",
"authMethods",
",",
"function",
"(",
"method",
")",
"{",
"_methodName",
"=",
"method",
".",
"name",
";",
"method",
"=",
"_",
".",
"merge",
"(",
"require",
"(",
"'../../'",
"+",
"_methodName",
")",
",",
"method",
")",
";",
"_method",
"[",
"method",
".",
"authType",
"]",
"=",
"method",
";",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"_errorHandler",
"(",
"_methodName",
")",
";",
"}",
"return",
"_method",
";",
"}"
] | requires an array of auth method objects
@param {Array} authMethods object array of auth methods
@return {Object} containing all required auth methods
@api private | [
"requires",
"an",
"array",
"of",
"auth",
"method",
"objects"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/methods.js#L43-L58 | |
21,824 | waterlock/waterlock | lib/methods.js | function(authMethod){
var method = {};
var _methodName = authMethod.name;
try{
var _method = _.merge(require('../../'+_methodName), authMethod);
method[_method.authType] = _method;
}catch(e){
this._errorHandler(_methodName);
}
return method;
} | javascript | function(authMethod){
var method = {};
var _methodName = authMethod.name;
try{
var _method = _.merge(require('../../'+_methodName), authMethod);
method[_method.authType] = _method;
}catch(e){
this._errorHandler(_methodName);
}
return method;
} | [
"function",
"(",
"authMethod",
")",
"{",
"var",
"method",
"=",
"{",
"}",
";",
"var",
"_methodName",
"=",
"authMethod",
".",
"name",
";",
"try",
"{",
"var",
"_method",
"=",
"_",
".",
"merge",
"(",
"require",
"(",
"'../../'",
"+",
"_methodName",
")",
",",
"authMethod",
")",
";",
"method",
"[",
"_method",
".",
"authType",
"]",
"=",
"_method",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"_errorHandler",
"(",
"_methodName",
")",
";",
"}",
"return",
"method",
";",
"}"
] | requires a single auth method by object
@param {Object} authMethod the auth method
@return {Object} containing all required auth methods
@api private | [
"requires",
"a",
"single",
"auth",
"method",
"by",
"object"
] | 088c7f9c641f626e6ebe9de4eec68f7eddf8d094 | https://github.com/waterlock/waterlock/blob/088c7f9c641f626e6ebe9de4eec68f7eddf8d094/lib/methods.js#L67-L79 | |
21,825 | fogus/lemonad | lib/lemonad.js | function(thing) {
if (L.existy(thing) && L.existy(thing.snapshot))
return thing.snapshot();
else
fail("snapshot not currently implemented")
//return L.snapshot(thing);
} | javascript | function(thing) {
if (L.existy(thing) && L.existy(thing.snapshot))
return thing.snapshot();
else
fail("snapshot not currently implemented")
//return L.snapshot(thing);
} | [
"function",
"(",
"thing",
")",
"{",
"if",
"(",
"L",
".",
"existy",
"(",
"thing",
")",
"&&",
"L",
".",
"existy",
"(",
"thing",
".",
"snapshot",
")",
")",
"return",
"thing",
".",
"snapshot",
"(",
")",
";",
"else",
"fail",
"(",
"\"snapshot not currently implemented\"",
")",
"//return L.snapshot(thing);",
"}"
] | Delegates down to the snapshot method if an object has one or clones the object outright if not. This is not as robust as it could be. Explore the possibility of pulling in Lo-Dash's impl. | [
"Delegates",
"down",
"to",
"the",
"snapshot",
"method",
"if",
"an",
"object",
"has",
"one",
"or",
"clones",
"the",
"object",
"outright",
"if",
"not",
".",
"This",
"is",
"not",
"as",
"robust",
"as",
"it",
"could",
"be",
".",
"Explore",
"the",
"possibility",
"of",
"pulling",
"in",
"Lo",
"-",
"Dash",
"s",
"impl",
"."
] | 49d32baa003d22cb22c577acab75865eab9e3dcb | https://github.com/fogus/lemonad/blob/49d32baa003d22cb22c577acab75865eab9e3dcb/lib/lemonad.js#L87-L93 | |
21,826 | fogus/lemonad | lib/lemonad.js | function(index) {
return function(array) {
if ((index < 0) || (index > array.length - 1)) L.fail("L.nth failure: attempting to index outside the bounds of the given array.");
return array[index];
};
} | javascript | function(index) {
return function(array) {
if ((index < 0) || (index > array.length - 1)) L.fail("L.nth failure: attempting to index outside the bounds of the given array.");
return array[index];
};
} | [
"function",
"(",
"index",
")",
"{",
"return",
"function",
"(",
"array",
")",
"{",
"if",
"(",
"(",
"index",
"<",
"0",
")",
"||",
"(",
"index",
">",
"array",
".",
"length",
"-",
"1",
")",
")",
"L",
".",
"fail",
"(",
"\"L.nth failure: attempting to index outside the bounds of the given array.\"",
")",
";",
"return",
"array",
"[",
"index",
"]",
";",
"}",
";",
"}"
] | A function to get at an index into an array | [
"A",
"function",
"to",
"get",
"at",
"an",
"index",
"into",
"an",
"array"
] | 49d32baa003d22cb22c577acab75865eab9e3dcb | https://github.com/fogus/lemonad/blob/49d32baa003d22cb22c577acab75865eab9e3dcb/lib/lemonad.js#L387-L392 | |
21,827 | fogus/lemonad | lib/lemonad.js | notify | function notify(oldVal, newVal) {
var count = 0;
for (var key in watchers) {
var watcher = watchers[key];
watcher.call(this, key, oldVal, newVal);
count++;
}
return count;
} | javascript | function notify(oldVal, newVal) {
var count = 0;
for (var key in watchers) {
var watcher = watchers[key];
watcher.call(this, key, oldVal, newVal);
count++;
}
return count;
} | [
"function",
"notify",
"(",
"oldVal",
",",
"newVal",
")",
"{",
"var",
"count",
"=",
"0",
";",
"for",
"(",
"var",
"key",
"in",
"watchers",
")",
"{",
"var",
"watcher",
"=",
"watchers",
"[",
"key",
"]",
";",
"watcher",
".",
"call",
"(",
"this",
",",
"key",
",",
"oldVal",
",",
"newVal",
")",
";",
"count",
"++",
";",
"}",
"return",
"count",
";",
"}"
] | The use of named function exprs is a temporary hack to make these methods play nicely with `invoker`. This is a non-portable technique. | [
"The",
"use",
"of",
"named",
"function",
"exprs",
"is",
"a",
"temporary",
"hack",
"to",
"make",
"these",
"methods",
"play",
"nicely",
"with",
"invoker",
".",
"This",
"is",
"a",
"non",
"-",
"portable",
"technique",
"."
] | 49d32baa003d22cb22c577acab75865eab9e3dcb | https://github.com/fogus/lemonad/blob/49d32baa003d22cb22c577acab75865eab9e3dcb/lib/lemonad.js#L880-L889 |
21,828 | jmreyes/passport-google-id-token | lib/passport-google-id-token/strategy.js | getGoogleCerts | function getGoogleCerts(kid, callback) {
request({uri: 'https://www.googleapis.com/oauth2/v1/certs'}, function(err, res, body) {
if (err || !res || res.statusCode != 200) {
err = err || new Error('error while retrieving Google certs');
callback(err);
} else {
try {
var keys = JSON.parse(body);
} catch (e) {
return callback(new Error('could not parse certs'));
}
callback(null, keys[kid]);
}
});
} | javascript | function getGoogleCerts(kid, callback) {
request({uri: 'https://www.googleapis.com/oauth2/v1/certs'}, function(err, res, body) {
if (err || !res || res.statusCode != 200) {
err = err || new Error('error while retrieving Google certs');
callback(err);
} else {
try {
var keys = JSON.parse(body);
} catch (e) {
return callback(new Error('could not parse certs'));
}
callback(null, keys[kid]);
}
});
} | [
"function",
"getGoogleCerts",
"(",
"kid",
",",
"callback",
")",
"{",
"request",
"(",
"{",
"uri",
":",
"'https://www.googleapis.com/oauth2/v1/certs'",
"}",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
"||",
"!",
"res",
"||",
"res",
".",
"statusCode",
"!=",
"200",
")",
"{",
"err",
"=",
"err",
"||",
"new",
"Error",
"(",
"'error while retrieving Google certs'",
")",
";",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"try",
"{",
"var",
"keys",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'could not parse certs'",
")",
")",
";",
"}",
"callback",
"(",
"null",
",",
"keys",
"[",
"kid",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] | Return the Google certificate that will be used for signature validation.
A custom function can be used instead when passed as an option in the Strategy
constructor. It can be interesting e.g. if caching is needed.
@param {String} kid The key id specified in the token
@param {Function} callback
@api protected | [
"Return",
"the",
"Google",
"certificate",
"that",
"will",
"be",
"used",
"for",
"signature",
"validation",
"."
] | 83cff7801407e6b14fe8097dc2b512c04edba5f8 | https://github.com/jmreyes/passport-google-id-token/blob/83cff7801407e6b14fe8097dc2b512c04edba5f8/lib/passport-google-id-token/strategy.js#L70-L85 |
21,829 | fogus/lemonad | examples/nationjs/shape.js | getArtists | function getArtists(library) {
var ret = [];
for (var i = 0; i < library.length; i++) {
ret.push(cell('artist', i, library));
}
return ret;
} | javascript | function getArtists(library) {
var ret = [];
for (var i = 0; i < library.length; i++) {
ret.push(cell('artist', i, library));
}
return ret;
} | [
"function",
"getArtists",
"(",
"library",
")",
"{",
"var",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"library",
".",
"length",
";",
"i",
"++",
")",
"{",
"ret",
".",
"push",
"(",
"cell",
"(",
"'artist'",
",",
"i",
",",
"library",
")",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | => "Om" | [
"=",
">",
"Om"
] | 49d32baa003d22cb22c577acab75865eab9e3dcb | https://github.com/fogus/lemonad/blob/49d32baa003d22cb22c577acab75865eab9e3dcb/examples/nationjs/shape.js#L29-L37 |
21,830 | fabito/botkit-storage-datastore | src/index.js | get | function get(datastore, kind, namespace) {
return function(id, cb) {
var keyParam = [kind, id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.get(key, function(err, entity) {
if (err)
return cb(err);
return cb(null, entity ? entity : null);
});
};
} | javascript | function get(datastore, kind, namespace) {
return function(id, cb) {
var keyParam = [kind, id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.get(key, function(err, entity) {
if (err)
return cb(err);
return cb(null, entity ? entity : null);
});
};
} | [
"function",
"get",
"(",
"datastore",
",",
"kind",
",",
"namespace",
")",
"{",
"return",
"function",
"(",
"id",
",",
"cb",
")",
"{",
"var",
"keyParam",
"=",
"[",
"kind",
",",
"id",
"]",
";",
"if",
"(",
"namespace",
")",
"{",
"keyParam",
"=",
"{",
"namespace",
":",
"namespace",
",",
"path",
":",
"keyParam",
"}",
";",
"}",
"var",
"key",
"=",
"datastore",
".",
"key",
"(",
"keyParam",
")",
";",
"datastore",
".",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"entity",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"return",
"cb",
"(",
"null",
",",
"entity",
"?",
"entity",
":",
"null",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Given a datastore reference and a kind, will return a function that will get a single entity by key
@param {Object} datastore A reference to the datastore Object
@param {String} kind The entity kind
@returns {Function} The get function | [
"Given",
"a",
"datastore",
"reference",
"and",
"a",
"kind",
"will",
"return",
"a",
"function",
"that",
"will",
"get",
"a",
"single",
"entity",
"by",
"key"
] | e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3 | https://github.com/fabito/botkit-storage-datastore/blob/e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3/src/index.js#L49-L67 |
21,831 | fabito/botkit-storage-datastore | src/index.js | save | function save(datastore, kind, namespace) {
return function(data, cb) {
var keyParam = [kind, data.id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.save({key: key, data: data}, cb);
};
} | javascript | function save(datastore, kind, namespace) {
return function(data, cb) {
var keyParam = [kind, data.id];
if (namespace) {
keyParam = {
namespace: namespace,
path: keyParam
};
}
var key = datastore.key(keyParam);
datastore.save({key: key, data: data}, cb);
};
} | [
"function",
"save",
"(",
"datastore",
",",
"kind",
",",
"namespace",
")",
"{",
"return",
"function",
"(",
"data",
",",
"cb",
")",
"{",
"var",
"keyParam",
"=",
"[",
"kind",
",",
"data",
".",
"id",
"]",
";",
"if",
"(",
"namespace",
")",
"{",
"keyParam",
"=",
"{",
"namespace",
":",
"namespace",
",",
"path",
":",
"keyParam",
"}",
";",
"}",
"var",
"key",
"=",
"datastore",
".",
"key",
"(",
"keyParam",
")",
";",
"datastore",
".",
"save",
"(",
"{",
"key",
":",
"key",
",",
"data",
":",
"data",
"}",
",",
"cb",
")",
";",
"}",
";",
"}"
] | Given a datastore reference and a kind, will return a function that will save an entity.
The object must have an id property
@param {Object} datastore A reference to the datastore Object
@param {String} kind The entity kind
@returns {Function} The save function | [
"Given",
"a",
"datastore",
"reference",
"and",
"a",
"kind",
"will",
"return",
"a",
"function",
"that",
"will",
"save",
"an",
"entity",
".",
"The",
"object",
"must",
"have",
"an",
"id",
"property"
] | e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3 | https://github.com/fabito/botkit-storage-datastore/blob/e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3/src/index.js#L98-L110 |
21,832 | fabito/botkit-storage-datastore | src/index.js | all | function all(datastore, kind, namespace) {
return function(cb) {
var query = null;
if (namespace) {
query = datastore.createQuery(namespace, kind);
} else {
query = datastore.createQuery(kind);
}
datastore.runQuery(query, function(err, entities) {
if (err)
return cb(err);
var list = (entities || []).map(function(entity) {
return entity;
});
cb(null, list);
});
};
} | javascript | function all(datastore, kind, namespace) {
return function(cb) {
var query = null;
if (namespace) {
query = datastore.createQuery(namespace, kind);
} else {
query = datastore.createQuery(kind);
}
datastore.runQuery(query, function(err, entities) {
if (err)
return cb(err);
var list = (entities || []).map(function(entity) {
return entity;
});
cb(null, list);
});
};
} | [
"function",
"all",
"(",
"datastore",
",",
"kind",
",",
"namespace",
")",
"{",
"return",
"function",
"(",
"cb",
")",
"{",
"var",
"query",
"=",
"null",
";",
"if",
"(",
"namespace",
")",
"{",
"query",
"=",
"datastore",
".",
"createQuery",
"(",
"namespace",
",",
"kind",
")",
";",
"}",
"else",
"{",
"query",
"=",
"datastore",
".",
"createQuery",
"(",
"kind",
")",
";",
"}",
"datastore",
".",
"runQuery",
"(",
"query",
",",
"function",
"(",
"err",
",",
"entities",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"var",
"list",
"=",
"(",
"entities",
"||",
"[",
"]",
")",
".",
"map",
"(",
"function",
"(",
"entity",
")",
"{",
"return",
"entity",
";",
"}",
")",
";",
"cb",
"(",
"null",
",",
"list",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Given a datastore reference and a kind, will return a function that will return all stored entities.
@param {Object} datastore A reference to the datastore Object
@param {String} kind The entity kind
@returns {Function} The all function | [
"Given",
"a",
"datastore",
"reference",
"and",
"a",
"kind",
"will",
"return",
"a",
"function",
"that",
"will",
"return",
"all",
"stored",
"entities",
"."
] | e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3 | https://github.com/fabito/botkit-storage-datastore/blob/e2becb4135bdf599fe01e4d4cf09cc0b7026ecb3/src/index.js#L119-L140 |
21,833 | aotaduy/eslint-plugin-spellcheck | rules/spell-checker.js | hasToSkipWord | function hasToSkipWord(word) {
if(word.length < options.minLength) return false;
if(lodash.find(options.skipWordIfMatch, function (aPattern) {
return word.match(aPattern);
})){
return false;
}
return true;
} | javascript | function hasToSkipWord(word) {
if(word.length < options.minLength) return false;
if(lodash.find(options.skipWordIfMatch, function (aPattern) {
return word.match(aPattern);
})){
return false;
}
return true;
} | [
"function",
"hasToSkipWord",
"(",
"word",
")",
"{",
"if",
"(",
"word",
".",
"length",
"<",
"options",
".",
"minLength",
")",
"return",
"false",
";",
"if",
"(",
"lodash",
".",
"find",
"(",
"options",
".",
"skipWordIfMatch",
",",
"function",
"(",
"aPattern",
")",
"{",
"return",
"word",
".",
"match",
"(",
"aPattern",
")",
";",
"}",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | returns false if the word has to be skipped
@param {string} word
@return {Boolean} false if skip; true if not | [
"returns",
"false",
"if",
"the",
"word",
"has",
"to",
"be",
"skipped"
] | 66882d0d1424b76c63e57c6ff6aad24b54ede7fc | https://github.com/aotaduy/eslint-plugin-spellcheck/blob/66882d0d1424b76c63e57c6ff6aad24b54ede7fc/rules/spell-checker.js#L214-L222 |
21,834 | tarunc/gulp-jsbeautifier | index.js | mergeOptions | function mergeOptions(pluginOptions) {
const defaultOptions = {
config: null,
debug: false,
css: {
file_types: ['.css', '.less', '.sass', '.scss'],
},
html: {
file_types: ['.html'],
},
js: {
file_types: ['.js', '.json'],
},
};
// Load 'file options'
const explorer = cosmiconfig('jsbeautify');
let explorerResult;
if (pluginOptions && pluginOptions.config) {
explorerResult = explorer.loadSync(path.resolve(pluginOptions.config));
} else {
explorerResult = explorer.searchSync();
}
let fileOptions;
if (explorerResult) {
fileOptions = explorerResult.config;
}
// Merge options
const finalOptions = mergeWith({}, defaultOptions, fileOptions, pluginOptions, (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
return undefined;
});
// Show debug messages
if (finalOptions.debug) {
if (fileOptions) {
log(`File options:\n${JSON.stringify(fileOptions, null, 2)}`);
}
log(`Final options:\n${JSON.stringify(finalOptions, null, 2)}`);
}
// Delete properties not used
delete finalOptions.config;
delete finalOptions.debug;
return finalOptions;
} | javascript | function mergeOptions(pluginOptions) {
const defaultOptions = {
config: null,
debug: false,
css: {
file_types: ['.css', '.less', '.sass', '.scss'],
},
html: {
file_types: ['.html'],
},
js: {
file_types: ['.js', '.json'],
},
};
// Load 'file options'
const explorer = cosmiconfig('jsbeautify');
let explorerResult;
if (pluginOptions && pluginOptions.config) {
explorerResult = explorer.loadSync(path.resolve(pluginOptions.config));
} else {
explorerResult = explorer.searchSync();
}
let fileOptions;
if (explorerResult) {
fileOptions = explorerResult.config;
}
// Merge options
const finalOptions = mergeWith({}, defaultOptions, fileOptions, pluginOptions, (objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
return undefined;
});
// Show debug messages
if (finalOptions.debug) {
if (fileOptions) {
log(`File options:\n${JSON.stringify(fileOptions, null, 2)}`);
}
log(`Final options:\n${JSON.stringify(finalOptions, null, 2)}`);
}
// Delete properties not used
delete finalOptions.config;
delete finalOptions.debug;
return finalOptions;
} | [
"function",
"mergeOptions",
"(",
"pluginOptions",
")",
"{",
"const",
"defaultOptions",
"=",
"{",
"config",
":",
"null",
",",
"debug",
":",
"false",
",",
"css",
":",
"{",
"file_types",
":",
"[",
"'.css'",
",",
"'.less'",
",",
"'.sass'",
",",
"'.scss'",
"]",
",",
"}",
",",
"html",
":",
"{",
"file_types",
":",
"[",
"'.html'",
"]",
",",
"}",
",",
"js",
":",
"{",
"file_types",
":",
"[",
"'.js'",
",",
"'.json'",
"]",
",",
"}",
",",
"}",
";",
"// Load 'file options'",
"const",
"explorer",
"=",
"cosmiconfig",
"(",
"'jsbeautify'",
")",
";",
"let",
"explorerResult",
";",
"if",
"(",
"pluginOptions",
"&&",
"pluginOptions",
".",
"config",
")",
"{",
"explorerResult",
"=",
"explorer",
".",
"loadSync",
"(",
"path",
".",
"resolve",
"(",
"pluginOptions",
".",
"config",
")",
")",
";",
"}",
"else",
"{",
"explorerResult",
"=",
"explorer",
".",
"searchSync",
"(",
")",
";",
"}",
"let",
"fileOptions",
";",
"if",
"(",
"explorerResult",
")",
"{",
"fileOptions",
"=",
"explorerResult",
".",
"config",
";",
"}",
"// Merge options",
"const",
"finalOptions",
"=",
"mergeWith",
"(",
"{",
"}",
",",
"defaultOptions",
",",
"fileOptions",
",",
"pluginOptions",
",",
"(",
"objValue",
",",
"srcValue",
")",
"=>",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"objValue",
")",
")",
"{",
"return",
"objValue",
".",
"concat",
"(",
"srcValue",
")",
";",
"}",
"return",
"undefined",
";",
"}",
")",
";",
"// Show debug messages",
"if",
"(",
"finalOptions",
".",
"debug",
")",
"{",
"if",
"(",
"fileOptions",
")",
"{",
"log",
"(",
"`",
"\\n",
"${",
"JSON",
".",
"stringify",
"(",
"fileOptions",
",",
"null",
",",
"2",
")",
"}",
"`",
")",
";",
"}",
"log",
"(",
"`",
"\\n",
"${",
"JSON",
".",
"stringify",
"(",
"finalOptions",
",",
"null",
",",
"2",
")",
"}",
"`",
")",
";",
"}",
"// Delete properties not used",
"delete",
"finalOptions",
".",
"config",
";",
"delete",
"finalOptions",
".",
"debug",
";",
"return",
"finalOptions",
";",
"}"
] | Merge options from different sources
@param {Object} pluginOptions The gulp-jsbeautifier options
@return {Object} The options | [
"Merge",
"options",
"from",
"different",
"sources"
] | 9e537eb625d4a9103851f3a2ecdc212280c9012b | https://github.com/tarunc/gulp-jsbeautifier/blob/9e537eb625d4a9103851f3a2ecdc212280c9012b/index.js#L17-L70 |
21,835 | tarunc/gulp-jsbeautifier | index.js | helper | function helper(pluginOptions, doValidation) {
const options = mergeOptions(pluginOptions);
return through.obj((file, encoding, callback) => {
let oldContent;
let newContent;
let type = null;
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
// Check if current file should be treated as JavaScript, HTML, CSS or if it should be ignored
['js', 'css', 'html'].some((value) => {
// Check if at least one element in 'file_types' is suffix of file basename
if (options[value].file_types.some(suffix => path.basename(file.path).endsWith(suffix))) {
type = value;
return true;
}
return false;
});
// Initialize properties for reporter
file.jsbeautify = {};
file.jsbeautify.type = type;
file.jsbeautify.beautified = false;
file.jsbeautify.canBeautify = false;
if (type) {
oldContent = file.contents.toString('utf8');
newContent = beautify[type](oldContent, options);
if (oldContent.toString() !== newContent.toString()) {
if (doValidation) {
file.jsbeautify.canBeautify = true;
} else {
file.contents = Buffer.from(newContent);
file.jsbeautify.beautified = true;
}
}
}
callback(null, file);
});
} | javascript | function helper(pluginOptions, doValidation) {
const options = mergeOptions(pluginOptions);
return through.obj((file, encoding, callback) => {
let oldContent;
let newContent;
let type = null;
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new PluginError(PLUGIN_NAME, 'Streaming not supported'));
return;
}
// Check if current file should be treated as JavaScript, HTML, CSS or if it should be ignored
['js', 'css', 'html'].some((value) => {
// Check if at least one element in 'file_types' is suffix of file basename
if (options[value].file_types.some(suffix => path.basename(file.path).endsWith(suffix))) {
type = value;
return true;
}
return false;
});
// Initialize properties for reporter
file.jsbeautify = {};
file.jsbeautify.type = type;
file.jsbeautify.beautified = false;
file.jsbeautify.canBeautify = false;
if (type) {
oldContent = file.contents.toString('utf8');
newContent = beautify[type](oldContent, options);
if (oldContent.toString() !== newContent.toString()) {
if (doValidation) {
file.jsbeautify.canBeautify = true;
} else {
file.contents = Buffer.from(newContent);
file.jsbeautify.beautified = true;
}
}
}
callback(null, file);
});
} | [
"function",
"helper",
"(",
"pluginOptions",
",",
"doValidation",
")",
"{",
"const",
"options",
"=",
"mergeOptions",
"(",
"pluginOptions",
")",
";",
"return",
"through",
".",
"obj",
"(",
"(",
"file",
",",
"encoding",
",",
"callback",
")",
"=>",
"{",
"let",
"oldContent",
";",
"let",
"newContent",
";",
"let",
"type",
"=",
"null",
";",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"callback",
"(",
"null",
",",
"file",
")",
";",
"return",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"callback",
"(",
"new",
"PluginError",
"(",
"PLUGIN_NAME",
",",
"'Streaming not supported'",
")",
")",
";",
"return",
";",
"}",
"// Check if current file should be treated as JavaScript, HTML, CSS or if it should be ignored",
"[",
"'js'",
",",
"'css'",
",",
"'html'",
"]",
".",
"some",
"(",
"(",
"value",
")",
"=>",
"{",
"// Check if at least one element in 'file_types' is suffix of file basename",
"if",
"(",
"options",
"[",
"value",
"]",
".",
"file_types",
".",
"some",
"(",
"suffix",
"=>",
"path",
".",
"basename",
"(",
"file",
".",
"path",
")",
".",
"endsWith",
"(",
"suffix",
")",
")",
")",
"{",
"type",
"=",
"value",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
";",
"// Initialize properties for reporter",
"file",
".",
"jsbeautify",
"=",
"{",
"}",
";",
"file",
".",
"jsbeautify",
".",
"type",
"=",
"type",
";",
"file",
".",
"jsbeautify",
".",
"beautified",
"=",
"false",
";",
"file",
".",
"jsbeautify",
".",
"canBeautify",
"=",
"false",
";",
"if",
"(",
"type",
")",
"{",
"oldContent",
"=",
"file",
".",
"contents",
".",
"toString",
"(",
"'utf8'",
")",
";",
"newContent",
"=",
"beautify",
"[",
"type",
"]",
"(",
"oldContent",
",",
"options",
")",
";",
"if",
"(",
"oldContent",
".",
"toString",
"(",
")",
"!==",
"newContent",
".",
"toString",
"(",
")",
")",
"{",
"if",
"(",
"doValidation",
")",
"{",
"file",
".",
"jsbeautify",
".",
"canBeautify",
"=",
"true",
";",
"}",
"else",
"{",
"file",
".",
"contents",
"=",
"Buffer",
".",
"from",
"(",
"newContent",
")",
";",
"file",
".",
"jsbeautify",
".",
"beautified",
"=",
"true",
";",
"}",
"}",
"}",
"callback",
"(",
"null",
",",
"file",
")",
";",
"}",
")",
";",
"}"
] | Beautify files or perform validation
@param {Object} pluginOptions The gulp-jsbeautifier parameter options
@param {boolean} doValidation Specifies whether perform validation only
@return {Object} The object stream | [
"Beautify",
"files",
"or",
"perform",
"validation"
] | 9e537eb625d4a9103851f3a2ecdc212280c9012b | https://github.com/tarunc/gulp-jsbeautifier/blob/9e537eb625d4a9103851f3a2ecdc212280c9012b/index.js#L78-L129 |
21,836 | Zenika/immutadot | packages/immutadot/src/core/flow.js | flow | function flow(...args) {
const fns = flatten(args)
.filter(fn => isFunction(fn))
.map(fn => fn.applier === undefined ? (
([obj, appliedPaths]) => [fn(obj), appliedPaths]
) : (
([obj, appliedPaths]) => [
fn.applier(obj, appliedPaths),
[...appliedPaths, fn.applier.path],
]
))
return obj => {
const [result] = fns.reduce(
(acc, fn) => fn(acc),
[obj, []],
)
return result
}
} | javascript | function flow(...args) {
const fns = flatten(args)
.filter(fn => isFunction(fn))
.map(fn => fn.applier === undefined ? (
([obj, appliedPaths]) => [fn(obj), appliedPaths]
) : (
([obj, appliedPaths]) => [
fn.applier(obj, appliedPaths),
[...appliedPaths, fn.applier.path],
]
))
return obj => {
const [result] = fns.reduce(
(acc, fn) => fn(acc),
[obj, []],
)
return result
}
} | [
"function",
"flow",
"(",
"...",
"args",
")",
"{",
"const",
"fns",
"=",
"flatten",
"(",
"args",
")",
".",
"filter",
"(",
"fn",
"=>",
"isFunction",
"(",
"fn",
")",
")",
".",
"map",
"(",
"fn",
"=>",
"fn",
".",
"applier",
"===",
"undefined",
"?",
"(",
"(",
"[",
"obj",
",",
"appliedPaths",
"]",
")",
"=>",
"[",
"fn",
"(",
"obj",
")",
",",
"appliedPaths",
"]",
")",
":",
"(",
"(",
"[",
"obj",
",",
"appliedPaths",
"]",
")",
"=>",
"[",
"fn",
".",
"applier",
"(",
"obj",
",",
"appliedPaths",
")",
",",
"[",
"...",
"appliedPaths",
",",
"fn",
".",
"applier",
".",
"path",
"]",
",",
"]",
")",
")",
"return",
"obj",
"=>",
"{",
"const",
"[",
"result",
"]",
"=",
"fns",
".",
"reduce",
"(",
"(",
"acc",
",",
"fn",
")",
"=>",
"fn",
"(",
"acc",
")",
",",
"[",
"obj",
",",
"[",
"]",
"]",
",",
")",
"return",
"result",
"}",
"}"
] | A function successively calling a list of functions.
@callback flowFunction
@memberof core
@param {*} arg The starting value
@returns {*} The resulting value
@since 1.0.0
Creates a function that will successively call all functions contained in <code>args</code>.<br/>
Each function is called with the result of the previous one.<br/>
Non functions <code>args</code> are tolerated and will be ignored.
@memberof core
@param {...(function|Array<function>)} args The functions to apply
@returns {core.flowFunction} A function successively calling function <code>args</code>
@since 1.0.0 | [
"A",
"function",
"successively",
"calling",
"a",
"list",
"of",
"functions",
"."
] | d6eaf9f8da4a7c0abdc71f1b01ec340130d7a970 | https://github.com/Zenika/immutadot/blob/d6eaf9f8da4a7c0abdc71f1b01ec340130d7a970/packages/immutadot/src/core/flow.js#L22-L40 |
21,837 | ueno-llc/styleguide | packages/eslint-plugin-internal/decorator-line-break.js | checkDecorator | function checkDecorator(decorator, value, node) {
const decoratorLine = decorator.loc.start.line;
const decoratorColumn = decorator.loc.end.column;
const valueLine = value.loc.start.line;
if (config === 'always') {
if (decoratorLine === valueLine) {
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: ALWAYS_MESSAGE,
});
}
} else {
if (decoratorLine !== valueLine) { // eslint-disable-line
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: NEVER_MESSAGE,
});
}
}
} | javascript | function checkDecorator(decorator, value, node) {
const decoratorLine = decorator.loc.start.line;
const decoratorColumn = decorator.loc.end.column;
const valueLine = value.loc.start.line;
if (config === 'always') {
if (decoratorLine === valueLine) {
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: ALWAYS_MESSAGE,
});
}
} else {
if (decoratorLine !== valueLine) { // eslint-disable-line
context.report({
node,
loc: { line: decoratorLine, column: decoratorColumn },
message: NEVER_MESSAGE,
});
}
}
} | [
"function",
"checkDecorator",
"(",
"decorator",
",",
"value",
",",
"node",
")",
"{",
"const",
"decoratorLine",
"=",
"decorator",
".",
"loc",
".",
"start",
".",
"line",
";",
"const",
"decoratorColumn",
"=",
"decorator",
".",
"loc",
".",
"end",
".",
"column",
";",
"const",
"valueLine",
"=",
"value",
".",
"loc",
".",
"start",
".",
"line",
";",
"if",
"(",
"config",
"===",
"'always'",
")",
"{",
"if",
"(",
"decoratorLine",
"===",
"valueLine",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"decoratorLine",
",",
"column",
":",
"decoratorColumn",
"}",
",",
"message",
":",
"ALWAYS_MESSAGE",
",",
"}",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"decoratorLine",
"!==",
"valueLine",
")",
"{",
"// eslint-disable-line",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"decoratorLine",
",",
"column",
":",
"decoratorColumn",
"}",
",",
"message",
":",
"NEVER_MESSAGE",
",",
"}",
")",
";",
"}",
"}",
"}"
] | Checks the given decorator node to check if a line break is needed.
@param {ASTNode} The decorator statement.
@param {ASTNode} The value statement.
@param {ASTNode} node The AST node of a BlockStatement.
@returns {void} undefined. | [
"Checks",
"the",
"given",
"decorator",
"node",
"to",
"check",
"if",
"a",
"line",
"break",
"is",
"needed",
"."
] | 708ce6d728b9189b2bcd71fb8b267c9b9eb33246 | https://github.com/ueno-llc/styleguide/blob/708ce6d728b9189b2bcd71fb8b267c9b9eb33246/packages/eslint-plugin-internal/decorator-line-break.js#L42-L64 |
21,838 | ueno-llc/styleguide | packages/eslint-plugin-internal/padded-blocks.js | getFirstBlockToken | function getFirstBlockToken(token) {
let prev;
let first = token;
do {
prev = first;
first = sourceCode.getTokenAfter(first, { includeComments: true });
} while (isComment(first) && first.loc.start.line === prev.loc.end.line);
return first;
} | javascript | function getFirstBlockToken(token) {
let prev;
let first = token;
do {
prev = first;
first = sourceCode.getTokenAfter(first, { includeComments: true });
} while (isComment(first) && first.loc.start.line === prev.loc.end.line);
return first;
} | [
"function",
"getFirstBlockToken",
"(",
"token",
")",
"{",
"let",
"prev",
";",
"let",
"first",
"=",
"token",
";",
"do",
"{",
"prev",
"=",
"first",
";",
"first",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"first",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"}",
"while",
"(",
"isComment",
"(",
"first",
")",
"&&",
"first",
".",
"loc",
".",
"start",
".",
"line",
"===",
"prev",
".",
"loc",
".",
"end",
".",
"line",
")",
";",
"return",
"first",
";",
"}"
] | Checks if the given token has a blank line after it.
@param {Token} token The token to check.
@returns {boolean} Whether or not the token is followed by a blank line. | [
"Checks",
"if",
"the",
"given",
"token",
"has",
"a",
"blank",
"line",
"after",
"it",
"."
] | 708ce6d728b9189b2bcd71fb8b267c9b9eb33246 | https://github.com/ueno-llc/styleguide/blob/708ce6d728b9189b2bcd71fb8b267c9b9eb33246/packages/eslint-plugin-internal/padded-blocks.js#L115-L125 |
21,839 | ueno-llc/styleguide | packages/eslint-plugin-internal/padded-blocks.js | getLastBlockToken | function getLastBlockToken(token) {
let last = token;
let next;
do {
next = last;
last = sourceCode.getTokenBefore(last, { includeComments: true });
} while (isComment(last) && last.loc.end.line === next.loc.start.line);
return last;
} | javascript | function getLastBlockToken(token) {
let last = token;
let next;
do {
next = last;
last = sourceCode.getTokenBefore(last, { includeComments: true });
} while (isComment(last) && last.loc.end.line === next.loc.start.line);
return last;
} | [
"function",
"getLastBlockToken",
"(",
"token",
")",
"{",
"let",
"last",
"=",
"token",
";",
"let",
"next",
";",
"do",
"{",
"next",
"=",
"last",
";",
"last",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"last",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"}",
"while",
"(",
"isComment",
"(",
"last",
")",
"&&",
"last",
".",
"loc",
".",
"end",
".",
"line",
"===",
"next",
".",
"loc",
".",
"start",
".",
"line",
")",
";",
"return",
"last",
";",
"}"
] | Checks if the given token is preceeded by a blank line.
@param {Token} token The token to check
@returns {boolean} Whether or not the token is preceeded by a blank line | [
"Checks",
"if",
"the",
"given",
"token",
"is",
"preceeded",
"by",
"a",
"blank",
"line",
"."
] | 708ce6d728b9189b2bcd71fb8b267c9b9eb33246 | https://github.com/ueno-llc/styleguide/blob/708ce6d728b9189b2bcd71fb8b267c9b9eb33246/packages/eslint-plugin-internal/padded-blocks.js#L132-L142 |
21,840 | ueno-llc/styleguide | packages/eslint-plugin-internal/padded-blocks.js | requirePaddingFor | function requirePaddingFor(node) {
switch (node.type) {
case 'BlockStatement':
return options.blocks;
case 'SwitchStatement':
return options.switches;
case 'ClassBody':
return options.classes;
/* istanbul ignore next */
default:
throw new Error('unreachable');
}
} | javascript | function requirePaddingFor(node) {
switch (node.type) {
case 'BlockStatement':
return options.blocks;
case 'SwitchStatement':
return options.switches;
case 'ClassBody':
return options.classes;
/* istanbul ignore next */
default:
throw new Error('unreachable');
}
} | [
"function",
"requirePaddingFor",
"(",
"node",
")",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"'BlockStatement'",
":",
"return",
"options",
".",
"blocks",
";",
"case",
"'SwitchStatement'",
":",
"return",
"options",
".",
"switches",
";",
"case",
"'ClassBody'",
":",
"return",
"options",
".",
"classes",
";",
"/* istanbul ignore next */",
"default",
":",
"throw",
"new",
"Error",
"(",
"'unreachable'",
")",
";",
"}",
"}"
] | Checks if a node should be padded, according to the rule config.
@param {ASTNode} node The AST node to check.
@returns {boolean} True if the node should be padded, false otherwise. | [
"Checks",
"if",
"a",
"node",
"should",
"be",
"padded",
"according",
"to",
"the",
"rule",
"config",
"."
] | 708ce6d728b9189b2bcd71fb8b267c9b9eb33246 | https://github.com/ueno-llc/styleguide/blob/708ce6d728b9189b2bcd71fb8b267c9b9eb33246/packages/eslint-plugin-internal/padded-blocks.js#L149-L164 |
21,841 | ueno-llc/styleguide | packages/eslint-plugin-internal/padded-blocks.js | checkPadding | function checkPadding(node, type) {
const openBrace = getOpenBrace(node);
const firstBlockToken = getFirstBlockToken(openBrace);
const tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true });
const closeBrace = sourceCode.getLastToken(node);
const lastBlockToken = getLastBlockToken(closeBrace);
const tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true });
const blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken);
const blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
const onlyTopPadding = context.options[0][type] === 'top';
const onlyBottomPadding = context.options[0][type] === 'bottom';
if (requirePaddingFor(node)) {
if (!blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.insertTextAfter(tokenBeforeFirst, '\n');
},
message: ALWAYS_MESSAGE,
});
}
if (!blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.insertTextBefore(tokenAfterLast, '\n');
},
message: ALWAYS_MESSAGE,
});
}
} else {
if (blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
if (blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
}
} | javascript | function checkPadding(node, type) {
const openBrace = getOpenBrace(node);
const firstBlockToken = getFirstBlockToken(openBrace);
const tokenBeforeFirst = sourceCode.getTokenBefore(firstBlockToken, { includeComments: true });
const closeBrace = sourceCode.getLastToken(node);
const lastBlockToken = getLastBlockToken(closeBrace);
const tokenAfterLast = sourceCode.getTokenAfter(lastBlockToken, { includeComments: true });
const blockHasTopPadding = isPaddingBetweenTokens(tokenBeforeFirst, firstBlockToken);
const blockHasBottomPadding = isPaddingBetweenTokens(lastBlockToken, tokenAfterLast);
const onlyTopPadding = context.options[0][type] === 'top';
const onlyBottomPadding = context.options[0][type] === 'bottom';
if (requirePaddingFor(node)) {
if (!blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.insertTextAfter(tokenBeforeFirst, '\n');
},
message: ALWAYS_MESSAGE,
});
}
if (!blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.insertTextBefore(tokenAfterLast, '\n');
},
message: ALWAYS_MESSAGE,
});
}
} else {
if (blockHasTopPadding && !onlyBottomPadding) {
context.report({
node,
loc: { line: tokenBeforeFirst.loc.start.line, column: tokenBeforeFirst.loc.start.column },
fix(fixer) {
return fixer.replaceTextRange([tokenBeforeFirst.range[1], firstBlockToken.range[0] - firstBlockToken.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
if (blockHasBottomPadding && !onlyTopPadding) {
context.report({
node,
loc: { line: tokenAfterLast.loc.end.line, column: tokenAfterLast.loc.end.column - 1 },
fix(fixer) {
return fixer.replaceTextRange([lastBlockToken.range[1], tokenAfterLast.range[0] - tokenAfterLast.loc.start.column], '\n');
},
message: NEVER_MESSAGE,
});
}
}
} | [
"function",
"checkPadding",
"(",
"node",
",",
"type",
")",
"{",
"const",
"openBrace",
"=",
"getOpenBrace",
"(",
"node",
")",
";",
"const",
"firstBlockToken",
"=",
"getFirstBlockToken",
"(",
"openBrace",
")",
";",
"const",
"tokenBeforeFirst",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"firstBlockToken",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"const",
"closeBrace",
"=",
"sourceCode",
".",
"getLastToken",
"(",
"node",
")",
";",
"const",
"lastBlockToken",
"=",
"getLastBlockToken",
"(",
"closeBrace",
")",
";",
"const",
"tokenAfterLast",
"=",
"sourceCode",
".",
"getTokenAfter",
"(",
"lastBlockToken",
",",
"{",
"includeComments",
":",
"true",
"}",
")",
";",
"const",
"blockHasTopPadding",
"=",
"isPaddingBetweenTokens",
"(",
"tokenBeforeFirst",
",",
"firstBlockToken",
")",
";",
"const",
"blockHasBottomPadding",
"=",
"isPaddingBetweenTokens",
"(",
"lastBlockToken",
",",
"tokenAfterLast",
")",
";",
"const",
"onlyTopPadding",
"=",
"context",
".",
"options",
"[",
"0",
"]",
"[",
"type",
"]",
"===",
"'top'",
";",
"const",
"onlyBottomPadding",
"=",
"context",
".",
"options",
"[",
"0",
"]",
"[",
"type",
"]",
"===",
"'bottom'",
";",
"if",
"(",
"requirePaddingFor",
"(",
"node",
")",
")",
"{",
"if",
"(",
"!",
"blockHasTopPadding",
"&&",
"!",
"onlyBottomPadding",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"tokenBeforeFirst",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"tokenBeforeFirst",
".",
"loc",
".",
"start",
".",
"column",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"insertTextAfter",
"(",
"tokenBeforeFirst",
",",
"'\\n'",
")",
";",
"}",
",",
"message",
":",
"ALWAYS_MESSAGE",
",",
"}",
")",
";",
"}",
"if",
"(",
"!",
"blockHasBottomPadding",
"&&",
"!",
"onlyTopPadding",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"tokenAfterLast",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"tokenAfterLast",
".",
"loc",
".",
"end",
".",
"column",
"-",
"1",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"insertTextBefore",
"(",
"tokenAfterLast",
",",
"'\\n'",
")",
";",
"}",
",",
"message",
":",
"ALWAYS_MESSAGE",
",",
"}",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"blockHasTopPadding",
"&&",
"!",
"onlyBottomPadding",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"tokenBeforeFirst",
".",
"loc",
".",
"start",
".",
"line",
",",
"column",
":",
"tokenBeforeFirst",
".",
"loc",
".",
"start",
".",
"column",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"tokenBeforeFirst",
".",
"range",
"[",
"1",
"]",
",",
"firstBlockToken",
".",
"range",
"[",
"0",
"]",
"-",
"firstBlockToken",
".",
"loc",
".",
"start",
".",
"column",
"]",
",",
"'\\n'",
")",
";",
"}",
",",
"message",
":",
"NEVER_MESSAGE",
",",
"}",
")",
";",
"}",
"if",
"(",
"blockHasBottomPadding",
"&&",
"!",
"onlyTopPadding",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"line",
":",
"tokenAfterLast",
".",
"loc",
".",
"end",
".",
"line",
",",
"column",
":",
"tokenAfterLast",
".",
"loc",
".",
"end",
".",
"column",
"-",
"1",
"}",
",",
"fix",
"(",
"fixer",
")",
"{",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"lastBlockToken",
".",
"range",
"[",
"1",
"]",
",",
"tokenAfterLast",
".",
"range",
"[",
"0",
"]",
"-",
"tokenAfterLast",
".",
"loc",
".",
"start",
".",
"column",
"]",
",",
"'\\n'",
")",
";",
"}",
",",
"message",
":",
"NEVER_MESSAGE",
",",
"}",
")",
";",
"}",
"}",
"}"
] | Checks the given BlockStatement node to be padded if the block is not empty.
@param {ASTNode} node The AST node of a BlockStatement.
@returns {void} undefined. | [
"Checks",
"the",
"given",
"BlockStatement",
"node",
"to",
"be",
"padded",
"if",
"the",
"block",
"is",
"not",
"empty",
"."
] | 708ce6d728b9189b2bcd71fb8b267c9b9eb33246 | https://github.com/ueno-llc/styleguide/blob/708ce6d728b9189b2bcd71fb8b267c9b9eb33246/packages/eslint-plugin-internal/padded-blocks.js#L171-L228 |
21,842 | zenozeng/p5.js-svg | src/p5.RendererSVG.js | function(element) {
if (element === elt) {
var wrapper = svgCanvas.getElement();
wrapper.parentNode.removeChild(wrapper);
}
} | javascript | function(element) {
if (element === elt) {
var wrapper = svgCanvas.getElement();
wrapper.parentNode.removeChild(wrapper);
}
} | [
"function",
"(",
"element",
")",
"{",
"if",
"(",
"element",
"===",
"elt",
")",
"{",
"var",
"wrapper",
"=",
"svgCanvas",
".",
"getElement",
"(",
")",
";",
"wrapper",
".",
"parentNode",
".",
"removeChild",
"(",
"wrapper",
")",
";",
"}",
"}"
] | fake parentNode.removeChild so that noCanvas will work | [
"fake",
"parentNode",
".",
"removeChild",
"so",
"that",
"noCanvas",
"will",
"work"
] | 67edbdbf1a19d4925afe8f30f724e1a0bc4e93bf | https://github.com/zenozeng/p5.js-svg/blob/67edbdbf1a19d4925afe8f30f724e1a0bc4e93bf/src/p5.RendererSVG.js#L26-L31 | |
21,843 | IonicaBizau/node-cli-graph | lib/index.js | CliGraph | function CliGraph(options) {
// Initialize variables
var self = this
, settings = self.options = Ul.deepMerge(options, CliGraph.defaults)
, i = 0
, character = null
, str = ""
;
self.graph = [];
settings.width *= settings.aRatio;
// Set the center of the graph
settings.center = Ul.merge(settings.center, {
x: settings.width / 2
, y: settings.height / 2
});
settings.center.x = Math.round(settings.center.x);
settings.center.y = Math.round(settings.center.y);
// Background
for (i = 0; i < settings.height; ++i) {
self.graph[i] = new Array(settings.width).join(settings.marks.background).split("");
}
// Center
self.graph[settings.center.y][settings.center.x] = settings.marks.center;
// Ox axis
for (i = 0; i < settings.width; ++i) {
character = settings.marks.hAxis;
if (i === settings.center.x) {
character = settings.marks.center;
} else if (i === settings.width - 1) {
character = settings.marks.rightArrow;
}
self.graph[settings.center.y][i] = character;
}
// Oy asis
for (i = 0; i < settings.height; ++i) {
character = settings.marks.vAxis;
if (i === settings.center.y) {
character = settings.marks.center;
} else if (i === 0) {
character = settings.marks.topArrow;
}
self.graph[i][settings.center.x] = character;
}
} | javascript | function CliGraph(options) {
// Initialize variables
var self = this
, settings = self.options = Ul.deepMerge(options, CliGraph.defaults)
, i = 0
, character = null
, str = ""
;
self.graph = [];
settings.width *= settings.aRatio;
// Set the center of the graph
settings.center = Ul.merge(settings.center, {
x: settings.width / 2
, y: settings.height / 2
});
settings.center.x = Math.round(settings.center.x);
settings.center.y = Math.round(settings.center.y);
// Background
for (i = 0; i < settings.height; ++i) {
self.graph[i] = new Array(settings.width).join(settings.marks.background).split("");
}
// Center
self.graph[settings.center.y][settings.center.x] = settings.marks.center;
// Ox axis
for (i = 0; i < settings.width; ++i) {
character = settings.marks.hAxis;
if (i === settings.center.x) {
character = settings.marks.center;
} else if (i === settings.width - 1) {
character = settings.marks.rightArrow;
}
self.graph[settings.center.y][i] = character;
}
// Oy asis
for (i = 0; i < settings.height; ++i) {
character = settings.marks.vAxis;
if (i === settings.center.y) {
character = settings.marks.center;
} else if (i === 0) {
character = settings.marks.topArrow;
}
self.graph[i][settings.center.x] = character;
}
} | [
"function",
"CliGraph",
"(",
"options",
")",
"{",
"// Initialize variables",
"var",
"self",
"=",
"this",
",",
"settings",
"=",
"self",
".",
"options",
"=",
"Ul",
".",
"deepMerge",
"(",
"options",
",",
"CliGraph",
".",
"defaults",
")",
",",
"i",
"=",
"0",
",",
"character",
"=",
"null",
",",
"str",
"=",
"\"\"",
";",
"self",
".",
"graph",
"=",
"[",
"]",
";",
"settings",
".",
"width",
"*=",
"settings",
".",
"aRatio",
";",
"// Set the center of the graph",
"settings",
".",
"center",
"=",
"Ul",
".",
"merge",
"(",
"settings",
".",
"center",
",",
"{",
"x",
":",
"settings",
".",
"width",
"/",
"2",
",",
"y",
":",
"settings",
".",
"height",
"/",
"2",
"}",
")",
";",
"settings",
".",
"center",
".",
"x",
"=",
"Math",
".",
"round",
"(",
"settings",
".",
"center",
".",
"x",
")",
";",
"settings",
".",
"center",
".",
"y",
"=",
"Math",
".",
"round",
"(",
"settings",
".",
"center",
".",
"y",
")",
";",
"// Background",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"settings",
".",
"height",
";",
"++",
"i",
")",
"{",
"self",
".",
"graph",
"[",
"i",
"]",
"=",
"new",
"Array",
"(",
"settings",
".",
"width",
")",
".",
"join",
"(",
"settings",
".",
"marks",
".",
"background",
")",
".",
"split",
"(",
"\"\"",
")",
";",
"}",
"// Center",
"self",
".",
"graph",
"[",
"settings",
".",
"center",
".",
"y",
"]",
"[",
"settings",
".",
"center",
".",
"x",
"]",
"=",
"settings",
".",
"marks",
".",
"center",
";",
"// Ox axis",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"settings",
".",
"width",
";",
"++",
"i",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"hAxis",
";",
"if",
"(",
"i",
"===",
"settings",
".",
"center",
".",
"x",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"center",
";",
"}",
"else",
"if",
"(",
"i",
"===",
"settings",
".",
"width",
"-",
"1",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"rightArrow",
";",
"}",
"self",
".",
"graph",
"[",
"settings",
".",
"center",
".",
"y",
"]",
"[",
"i",
"]",
"=",
"character",
";",
"}",
"// Oy asis",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"settings",
".",
"height",
";",
"++",
"i",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"vAxis",
";",
"if",
"(",
"i",
"===",
"settings",
".",
"center",
".",
"y",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"center",
";",
"}",
"else",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"character",
"=",
"settings",
".",
"marks",
".",
"topArrow",
";",
"}",
"self",
".",
"graph",
"[",
"i",
"]",
"[",
"settings",
".",
"center",
".",
"x",
"]",
"=",
"character",
";",
"}",
"}"
] | CliGraph
Creates a new CliGraph instance.
Example:
```js
var g = new CliGraph();
```
@name CliGraph
@function
@param {Object} options An object containing the following fields:
- `height` (Number): The graph height (default: `40`).
- `width` (Number): The graph width (default: `60`).
- `aRatio` (Number): The horizontal aspect ratio (default: `2`).
- `center` (Object): An object containing:
- `x` (Number): The `x` origin (default: `width / 2`)
- `y` (Number): The `y` origin (default: `height / 2`)
- `marks` (Object): An object containing:
- `hAxis` (String): The character for drawing horizontal axis (default `"─"`).
- `vAxis` (String): The character for drawing vertical axis (default "│").
- `center` (String): The character for axis intersection (default `"┼"`).
- `point` (String): The character for drawing points (default `"•"`).
- `rightArrow` (String): The character for drawing the right arrow (default `"▶"`).
- `topArrow` (String): The character for drawing the top arrow (default `"▲"`).
- `background` (String): The background character (default `" "`).
@return {CliGraph} The CliGraph instance. | [
"CliGraph",
"Creates",
"a",
"new",
"CliGraph",
"instance",
"."
] | f0b4ac85be0cdd9063834c3eaad39eef78288e2d | https://github.com/IonicaBizau/node-cli-graph/blob/f0b4ac85be0cdd9063834c3eaad39eef78288e2d/lib/index.js#L35-L89 |
21,844 | InCar/ali-mns | index.js | Subscription | function Subscription(name, topic) {
this._pattern = "%s://%s.mns.%s.aliyuncs.com/topics/%s/subscriptions/%s";
this._name = name;
this._topic = topic;
// make url
this._urlAttr = this.makeAttrURL();
// create the OpenStack object
this._openStack = new AliMNS.OpenStack(topic.getAccount());
} | javascript | function Subscription(name, topic) {
this._pattern = "%s://%s.mns.%s.aliyuncs.com/topics/%s/subscriptions/%s";
this._name = name;
this._topic = topic;
// make url
this._urlAttr = this.makeAttrURL();
// create the OpenStack object
this._openStack = new AliMNS.OpenStack(topic.getAccount());
} | [
"function",
"Subscription",
"(",
"name",
",",
"topic",
")",
"{",
"this",
".",
"_pattern",
"=",
"\"%s://%s.mns.%s.aliyuncs.com/topics/%s/subscriptions/%s\"",
";",
"this",
".",
"_name",
"=",
"name",
";",
"this",
".",
"_topic",
"=",
"topic",
";",
"// make url",
"this",
".",
"_urlAttr",
"=",
"this",
".",
"makeAttrURL",
"(",
")",
";",
"// create the OpenStack object",
"this",
".",
"_openStack",
"=",
"new",
"AliMNS",
".",
"OpenStack",
"(",
"topic",
".",
"getAccount",
"(",
")",
")",
";",
"}"
] | The constructor. name & topic is required. | [
"The",
"constructor",
".",
"name",
"&",
"topic",
"is",
"required",
"."
] | 4a2834281f2b4d862bcbfc0b55a050a19cf57c4b | https://github.com/InCar/ali-mns/blob/4a2834281f2b4d862bcbfc0b55a050a19cf57c4b/index.js#L1180-L1188 |
21,845 | mvhenderson/pandoc-filter-node | index.js | filter | function filter(data, action, format) {
return walk(data, action, format, data.meta || data[0].unMeta);
} | javascript | function filter(data, action, format) {
return walk(data, action, format, data.meta || data[0].unMeta);
} | [
"function",
"filter",
"(",
"data",
",",
"action",
",",
"format",
")",
"{",
"return",
"walk",
"(",
"data",
",",
"action",
",",
"format",
",",
"data",
".",
"meta",
"||",
"data",
"[",
"0",
"]",
".",
"unMeta",
")",
";",
"}"
] | Filter the given object | [
"Filter",
"the",
"given",
"object"
] | d37259e8b0af8f73764ac2ca00007a9447ffe0dd | https://github.com/mvhenderson/pandoc-filter-node/blob/d37259e8b0af8f73764ac2ca00007a9447ffe0dd/index.js#L35-L37 |
21,846 | mvhenderson/pandoc-filter-node | index.js | walk | function walk(x, action, format, meta) {
if (Array.isArray(x)) {
var array = [];
x.forEach(function (item) {
if (item === Object(item) && item.t) {
var res = action(item.t, item.c || [], format, meta)
if (!res) {
array.push(walk(item, action, format, meta));
}
else if (Array.isArray(res)) {
res.forEach(function (z) {
array.push(walk(z, action, format, meta));
});
}
else {
array.push(walk(res, action, format, meta));
}
}
else {
array.push(walk(item, action, format, meta));
}
});
return array;
}
else if (x === Object(x)) {
var obj = {};
Object.keys(x).forEach(function (k) {
obj[k] = walk(x[k], action, format, meta);
});
return obj;
}
return x;
} | javascript | function walk(x, action, format, meta) {
if (Array.isArray(x)) {
var array = [];
x.forEach(function (item) {
if (item === Object(item) && item.t) {
var res = action(item.t, item.c || [], format, meta)
if (!res) {
array.push(walk(item, action, format, meta));
}
else if (Array.isArray(res)) {
res.forEach(function (z) {
array.push(walk(z, action, format, meta));
});
}
else {
array.push(walk(res, action, format, meta));
}
}
else {
array.push(walk(item, action, format, meta));
}
});
return array;
}
else if (x === Object(x)) {
var obj = {};
Object.keys(x).forEach(function (k) {
obj[k] = walk(x[k], action, format, meta);
});
return obj;
}
return x;
} | [
"function",
"walk",
"(",
"x",
",",
"action",
",",
"format",
",",
"meta",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"x",
")",
")",
"{",
"var",
"array",
"=",
"[",
"]",
";",
"x",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"if",
"(",
"item",
"===",
"Object",
"(",
"item",
")",
"&&",
"item",
".",
"t",
")",
"{",
"var",
"res",
"=",
"action",
"(",
"item",
".",
"t",
",",
"item",
".",
"c",
"||",
"[",
"]",
",",
"format",
",",
"meta",
")",
"if",
"(",
"!",
"res",
")",
"{",
"array",
".",
"push",
"(",
"walk",
"(",
"item",
",",
"action",
",",
"format",
",",
"meta",
")",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"res",
")",
")",
"{",
"res",
".",
"forEach",
"(",
"function",
"(",
"z",
")",
"{",
"array",
".",
"push",
"(",
"walk",
"(",
"z",
",",
"action",
",",
"format",
",",
"meta",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"array",
".",
"push",
"(",
"walk",
"(",
"res",
",",
"action",
",",
"format",
",",
"meta",
")",
")",
";",
"}",
"}",
"else",
"{",
"array",
".",
"push",
"(",
"walk",
"(",
"item",
",",
"action",
",",
"format",
",",
"meta",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"array",
";",
"}",
"else",
"if",
"(",
"x",
"===",
"Object",
"(",
"x",
")",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"x",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"obj",
"[",
"k",
"]",
"=",
"walk",
"(",
"x",
"[",
"k",
"]",
",",
"action",
",",
"format",
",",
"meta",
")",
";",
"}",
")",
";",
"return",
"obj",
";",
"}",
"return",
"x",
";",
"}"
] | Walk a tree, applying an action to every object.
@param {Object} x The object to traverse
@param {Function} action Callback to apply to each item
@param {String} format Output format
@param {Object} meta Pandoc metadata
@return {Object} The modified tree | [
"Walk",
"a",
"tree",
"applying",
"an",
"action",
"to",
"every",
"object",
"."
] | d37259e8b0af8f73764ac2ca00007a9447ffe0dd | https://github.com/mvhenderson/pandoc-filter-node/blob/d37259e8b0af8f73764ac2ca00007a9447ffe0dd/index.js#L47-L79 |
21,847 | mvhenderson/pandoc-filter-node | index.js | stringify | function stringify(x) {
if (x === Object(x) && x.t === 'MetaString') return x.c;
var result = [];
var go = function (key, val) {
if (key === 'Str') result.push(val);
else if (key === 'Code') result.push(val[1]);
else if (key === 'Math') result.push(val[1]);
else if (key === 'LineBreak') result.push(' ');
else if (key === 'Space') result.push(' ');
};
walk(x, go, '', {});
return result.join('');
} | javascript | function stringify(x) {
if (x === Object(x) && x.t === 'MetaString') return x.c;
var result = [];
var go = function (key, val) {
if (key === 'Str') result.push(val);
else if (key === 'Code') result.push(val[1]);
else if (key === 'Math') result.push(val[1]);
else if (key === 'LineBreak') result.push(' ');
else if (key === 'Space') result.push(' ');
};
walk(x, go, '', {});
return result.join('');
} | [
"function",
"stringify",
"(",
"x",
")",
"{",
"if",
"(",
"x",
"===",
"Object",
"(",
"x",
")",
"&&",
"x",
".",
"t",
"===",
"'MetaString'",
")",
"return",
"x",
".",
"c",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"go",
"=",
"function",
"(",
"key",
",",
"val",
")",
"{",
"if",
"(",
"key",
"===",
"'Str'",
")",
"result",
".",
"push",
"(",
"val",
")",
";",
"else",
"if",
"(",
"key",
"===",
"'Code'",
")",
"result",
".",
"push",
"(",
"val",
"[",
"1",
"]",
")",
";",
"else",
"if",
"(",
"key",
"===",
"'Math'",
")",
"result",
".",
"push",
"(",
"val",
"[",
"1",
"]",
")",
";",
"else",
"if",
"(",
"key",
"===",
"'LineBreak'",
")",
"result",
".",
"push",
"(",
"' '",
")",
";",
"else",
"if",
"(",
"key",
"===",
"'Space'",
")",
"result",
".",
"push",
"(",
"' '",
")",
";",
"}",
";",
"walk",
"(",
"x",
",",
"go",
",",
"''",
",",
"{",
"}",
")",
";",
"return",
"result",
".",
"join",
"(",
"''",
")",
";",
"}"
] | Walks the tree x and returns concatenated string content, leaving out all
formatting.
@param {Object} x The object to walk
@return {String} JSON string | [
"Walks",
"the",
"tree",
"x",
"and",
"returns",
"concatenated",
"string",
"content",
"leaving",
"out",
"all",
"formatting",
"."
] | d37259e8b0af8f73764ac2ca00007a9447ffe0dd | https://github.com/mvhenderson/pandoc-filter-node/blob/d37259e8b0af8f73764ac2ca00007a9447ffe0dd/index.js#L87-L100 |
21,848 | mvhenderson/pandoc-filter-node | index.js | attributes | function attributes(attrs) {
attrs = attrs || {};
var ident = attrs.id || '';
var classes = attrs.classes || [];
var keyvals = [];
Object.keys(attrs).forEach(function (k) {
if (k !== 'classes' && k !== 'id') keyvals.push([k,attrs[k]]);
});
return [ident, classes, keyvals];
} | javascript | function attributes(attrs) {
attrs = attrs || {};
var ident = attrs.id || '';
var classes = attrs.classes || [];
var keyvals = [];
Object.keys(attrs).forEach(function (k) {
if (k !== 'classes' && k !== 'id') keyvals.push([k,attrs[k]]);
});
return [ident, classes, keyvals];
} | [
"function",
"attributes",
"(",
"attrs",
")",
"{",
"attrs",
"=",
"attrs",
"||",
"{",
"}",
";",
"var",
"ident",
"=",
"attrs",
".",
"id",
"||",
"''",
";",
"var",
"classes",
"=",
"attrs",
".",
"classes",
"||",
"[",
"]",
";",
"var",
"keyvals",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"attrs",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"k",
"!==",
"'classes'",
"&&",
"k",
"!==",
"'id'",
")",
"keyvals",
".",
"push",
"(",
"[",
"k",
",",
"attrs",
"[",
"k",
"]",
"]",
")",
";",
"}",
")",
";",
"return",
"[",
"ident",
",",
"classes",
",",
"keyvals",
"]",
";",
"}"
] | Returns an attribute list, constructed from the dictionary attrs.
@param {Object} attrs Attribute dictionary
@return {Array} Attribute list | [
"Returns",
"an",
"attribute",
"list",
"constructed",
"from",
"the",
"dictionary",
"attrs",
"."
] | d37259e8b0af8f73764ac2ca00007a9447ffe0dd | https://github.com/mvhenderson/pandoc-filter-node/blob/d37259e8b0af8f73764ac2ca00007a9447ffe0dd/index.js#L107-L116 |
21,849 | mvhenderson/pandoc-filter-node | index.js | elt | function elt(eltType, numargs) {
return function () {
var args = Array.prototype.slice.call(arguments);
var len = args.length;
if (len !== numargs)
throw eltType + ' expects ' + numargs + ' arguments, but given ' + len;
return {'t':eltType,'c':(len === 1 ? args[0] : args)};
};
} | javascript | function elt(eltType, numargs) {
return function () {
var args = Array.prototype.slice.call(arguments);
var len = args.length;
if (len !== numargs)
throw eltType + ' expects ' + numargs + ' arguments, but given ' + len;
return {'t':eltType,'c':(len === 1 ? args[0] : args)};
};
} | [
"function",
"elt",
"(",
"eltType",
",",
"numargs",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"len",
"=",
"args",
".",
"length",
";",
"if",
"(",
"len",
"!==",
"numargs",
")",
"throw",
"eltType",
"+",
"' expects '",
"+",
"numargs",
"+",
"' arguments, but given '",
"+",
"len",
";",
"return",
"{",
"'t'",
":",
"eltType",
",",
"'c'",
":",
"(",
"len",
"===",
"1",
"?",
"args",
"[",
"0",
"]",
":",
"args",
")",
"}",
";",
"}",
";",
"}"
] | Utility for creating constructor functions | [
"Utility",
"for",
"creating",
"constructor",
"functions"
] | d37259e8b0af8f73764ac2ca00007a9447ffe0dd | https://github.com/mvhenderson/pandoc-filter-node/blob/d37259e8b0af8f73764ac2ca00007a9447ffe0dd/index.js#L119-L127 |
21,850 | gratifyguy/botkit-mock | lib/SlackBotWorker/api.js | postForm | function postForm(url, formData, cb, multipart) {
cb = cb || noop;
botkit.debug('** API CALL: ' + url);
if (Array.isArray(api.logByKey[url])) {
api.logByKey[url].push(formData);
} else {
api.logByKey[url] = [formData];
}
storage.process(url, formData, cb);
} | javascript | function postForm(url, formData, cb, multipart) {
cb = cb || noop;
botkit.debug('** API CALL: ' + url);
if (Array.isArray(api.logByKey[url])) {
api.logByKey[url].push(formData);
} else {
api.logByKey[url] = [formData];
}
storage.process(url, formData, cb);
} | [
"function",
"postForm",
"(",
"url",
",",
"formData",
",",
"cb",
",",
"multipart",
")",
"{",
"cb",
"=",
"cb",
"||",
"noop",
";",
"botkit",
".",
"debug",
"(",
"'** API CALL: '",
"+",
"url",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"api",
".",
"logByKey",
"[",
"url",
"]",
")",
")",
"{",
"api",
".",
"logByKey",
"[",
"url",
"]",
".",
"push",
"(",
"formData",
")",
";",
"}",
"else",
"{",
"api",
".",
"logByKey",
"[",
"url",
"]",
"=",
"[",
"formData",
"]",
";",
"}",
"storage",
".",
"process",
"(",
"url",
",",
"formData",
",",
"cb",
")",
";",
"}"
] | Makes a POST request as a form to the given url with the options as data
@param {string} url The URL to POST to
@param {Object} formData The data to POST as a form
@param {function=} cb An optional NodeJS style callback when the POST completes or errors out. | [
"Makes",
"a",
"POST",
"request",
"as",
"a",
"form",
"to",
"the",
"given",
"url",
"with",
"the",
"options",
"as",
"data"
] | 9b862b5bd4f8742432b8e47384351bd9ea3a9ed2 | https://github.com/gratifyguy/botkit-mock/blob/9b862b5bd4f8742432b8e47384351bd9ea3a9ed2/lib/SlackBotWorker/api.js#L229-L241 |
21,851 | gratifyguy/botkit-mock | examples/botkit-starter-slack/skills/sample_taskbot.js | generateTaskList | function generateTaskList (user) {
var text = '';
for (var t = 0; t < user.tasks.length; t++) {
text = text + '> `' + (t + 1) + '`) ' + user.tasks[t] + '\n';
}
return text;
} | javascript | function generateTaskList (user) {
var text = '';
for (var t = 0; t < user.tasks.length; t++) {
text = text + '> `' + (t + 1) + '`) ' + user.tasks[t] + '\n';
}
return text;
} | [
"function",
"generateTaskList",
"(",
"user",
")",
"{",
"var",
"text",
"=",
"''",
";",
"for",
"(",
"var",
"t",
"=",
"0",
";",
"t",
"<",
"user",
".",
"tasks",
".",
"length",
";",
"t",
"++",
")",
"{",
"text",
"=",
"text",
"+",
"'> `'",
"+",
"(",
"t",
"+",
"1",
")",
"+",
"'`) '",
"+",
"user",
".",
"tasks",
"[",
"t",
"]",
"+",
"'\\n'",
";",
"}",
"return",
"text",
";",
"}"
] | simple function to generate the text of the task list so that it can be used in various places | [
"simple",
"function",
"to",
"generate",
"the",
"text",
"of",
"the",
"task",
"list",
"so",
"that",
"it",
"can",
"be",
"used",
"in",
"various",
"places"
] | 9b862b5bd4f8742432b8e47384351bd9ea3a9ed2 | https://github.com/gratifyguy/botkit-mock/blob/9b862b5bd4f8742432b8e47384351bd9ea3a9ed2/examples/botkit-starter-slack/skills/sample_taskbot.js#L122-L132 |
21,852 | josephfrazier/prettier_d | src/common/util.js | skipNewline | function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const atIndex = text.charAt(index);
if (backwards) {
if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
return index - 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index - 1;
}
} else {
if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
return index + 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index + 1;
}
}
return index;
} | javascript | function skipNewline(text, index, opts) {
const backwards = opts && opts.backwards;
if (index === false) {
return false;
}
const atIndex = text.charAt(index);
if (backwards) {
if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
return index - 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index - 1;
}
} else {
if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
return index + 2;
}
if (
atIndex === "\n" ||
atIndex === "\r" ||
atIndex === "\u2028" ||
atIndex === "\u2029"
) {
return index + 1;
}
}
return index;
} | [
"function",
"skipNewline",
"(",
"text",
",",
"index",
",",
"opts",
")",
"{",
"const",
"backwards",
"=",
"opts",
"&&",
"opts",
".",
"backwards",
";",
"if",
"(",
"index",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"const",
"atIndex",
"=",
"text",
".",
"charAt",
"(",
"index",
")",
";",
"if",
"(",
"backwards",
")",
"{",
"if",
"(",
"text",
".",
"charAt",
"(",
"index",
"-",
"1",
")",
"===",
"\"\\r\"",
"&&",
"atIndex",
"===",
"\"\\n\"",
")",
"{",
"return",
"index",
"-",
"2",
";",
"}",
"if",
"(",
"atIndex",
"===",
"\"\\n\"",
"||",
"atIndex",
"===",
"\"\\r\"",
"||",
"atIndex",
"===",
"\"\\u2028\"",
"||",
"atIndex",
"===",
"\"\\u2029\"",
")",
"{",
"return",
"index",
"-",
"1",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"atIndex",
"===",
"\"\\r\"",
"&&",
"text",
".",
"charAt",
"(",
"index",
"+",
"1",
")",
"===",
"\"\\n\"",
")",
"{",
"return",
"index",
"+",
"2",
";",
"}",
"if",
"(",
"atIndex",
"===",
"\"\\n\"",
"||",
"atIndex",
"===",
"\"\\r\"",
"||",
"atIndex",
"===",
"\"\\u2028\"",
"||",
"atIndex",
"===",
"\"\\u2029\"",
")",
"{",
"return",
"index",
"+",
"1",
";",
"}",
"}",
"return",
"index",
";",
"}"
] | This one doesn't use the above helper function because it wants to test \r\n in order and `skip` doesn't support ordering and we only want to skip one newline. It's simple to implement. | [
"This",
"one",
"doesn",
"t",
"use",
"the",
"above",
"helper",
"function",
"because",
"it",
"wants",
"to",
"test",
"\\",
"r",
"\\",
"n",
"in",
"order",
"and",
"skip",
"doesn",
"t",
"support",
"ordering",
"and",
"we",
"only",
"want",
"to",
"skip",
"one",
"newline",
".",
"It",
"s",
"simple",
"to",
"implement",
"."
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/common/util.js#L111-L145 |
21,853 | josephfrazier/prettier_d | src/main/options.js | normalize | function normalize(options, opts) {
opts = opts || {};
const rawOptions = Object.assign({}, options);
const supportOptions = getSupportInfo(null, {
plugins: options.plugins,
showUnreleased: true,
showDeprecated: true
}).options;
const defaults = supportOptions.reduce(
(reduced, optionInfo) =>
optionInfo.default !== undefined
? Object.assign(reduced, { [optionInfo.name]: optionInfo.default })
: reduced,
Object.assign({}, hiddenDefaults)
);
if (!rawOptions.parser) {
if (!rawOptions.filepath) {
const logger = opts.logger || console;
logger.warn(
"No parser and no filepath given, using 'babel' the parser now " +
"but this will throw an error in the future. " +
"Please specify a parser or a filepath so one can be inferred."
);
rawOptions.parser = "babel";
} else {
rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
if (!rawOptions.parser) {
throw new UndefinedParserError(
`No parser could be inferred for file: ${rawOptions.filepath}`
);
}
}
}
const parser = resolveParser(
normalizer.normalizeApiOptions(
rawOptions,
[supportOptions.find(x => x.name === "parser")],
{ passThrough: true, logger: false }
)
);
rawOptions.astFormat = parser.astFormat;
rawOptions.locEnd = parser.locEnd;
rawOptions.locStart = parser.locStart;
const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat];
const pluginDefaults = supportOptions
.filter(
optionInfo =>
optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name]
)
.reduce(
(reduced, optionInfo) =>
Object.assign(reduced, {
[optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
}),
{}
);
const mixedDefaults = Object.assign({}, defaults, pluginDefaults);
Object.keys(mixedDefaults).forEach(k => {
if (rawOptions[k] == null) {
rawOptions[k] = mixedDefaults[k];
}
});
if (rawOptions.parser === "json") {
rawOptions.trailingComma = "none";
}
return normalizer.normalizeApiOptions(
rawOptions,
supportOptions,
Object.assign({ passThrough: Object.keys(hiddenDefaults) }, opts)
);
} | javascript | function normalize(options, opts) {
opts = opts || {};
const rawOptions = Object.assign({}, options);
const supportOptions = getSupportInfo(null, {
plugins: options.plugins,
showUnreleased: true,
showDeprecated: true
}).options;
const defaults = supportOptions.reduce(
(reduced, optionInfo) =>
optionInfo.default !== undefined
? Object.assign(reduced, { [optionInfo.name]: optionInfo.default })
: reduced,
Object.assign({}, hiddenDefaults)
);
if (!rawOptions.parser) {
if (!rawOptions.filepath) {
const logger = opts.logger || console;
logger.warn(
"No parser and no filepath given, using 'babel' the parser now " +
"but this will throw an error in the future. " +
"Please specify a parser or a filepath so one can be inferred."
);
rawOptions.parser = "babel";
} else {
rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
if (!rawOptions.parser) {
throw new UndefinedParserError(
`No parser could be inferred for file: ${rawOptions.filepath}`
);
}
}
}
const parser = resolveParser(
normalizer.normalizeApiOptions(
rawOptions,
[supportOptions.find(x => x.name === "parser")],
{ passThrough: true, logger: false }
)
);
rawOptions.astFormat = parser.astFormat;
rawOptions.locEnd = parser.locEnd;
rawOptions.locStart = parser.locStart;
const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat];
const pluginDefaults = supportOptions
.filter(
optionInfo =>
optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name]
)
.reduce(
(reduced, optionInfo) =>
Object.assign(reduced, {
[optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
}),
{}
);
const mixedDefaults = Object.assign({}, defaults, pluginDefaults);
Object.keys(mixedDefaults).forEach(k => {
if (rawOptions[k] == null) {
rawOptions[k] = mixedDefaults[k];
}
});
if (rawOptions.parser === "json") {
rawOptions.trailingComma = "none";
}
return normalizer.normalizeApiOptions(
rawOptions,
supportOptions,
Object.assign({ passThrough: Object.keys(hiddenDefaults) }, opts)
);
} | [
"function",
"normalize",
"(",
"options",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"const",
"rawOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"const",
"supportOptions",
"=",
"getSupportInfo",
"(",
"null",
",",
"{",
"plugins",
":",
"options",
".",
"plugins",
",",
"showUnreleased",
":",
"true",
",",
"showDeprecated",
":",
"true",
"}",
")",
".",
"options",
";",
"const",
"defaults",
"=",
"supportOptions",
".",
"reduce",
"(",
"(",
"reduced",
",",
"optionInfo",
")",
"=>",
"optionInfo",
".",
"default",
"!==",
"undefined",
"?",
"Object",
".",
"assign",
"(",
"reduced",
",",
"{",
"[",
"optionInfo",
".",
"name",
"]",
":",
"optionInfo",
".",
"default",
"}",
")",
":",
"reduced",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"hiddenDefaults",
")",
")",
";",
"if",
"(",
"!",
"rawOptions",
".",
"parser",
")",
"{",
"if",
"(",
"!",
"rawOptions",
".",
"filepath",
")",
"{",
"const",
"logger",
"=",
"opts",
".",
"logger",
"||",
"console",
";",
"logger",
".",
"warn",
"(",
"\"No parser and no filepath given, using 'babel' the parser now \"",
"+",
"\"but this will throw an error in the future. \"",
"+",
"\"Please specify a parser or a filepath so one can be inferred.\"",
")",
";",
"rawOptions",
".",
"parser",
"=",
"\"babel\"",
";",
"}",
"else",
"{",
"rawOptions",
".",
"parser",
"=",
"inferParser",
"(",
"rawOptions",
".",
"filepath",
",",
"rawOptions",
".",
"plugins",
")",
";",
"if",
"(",
"!",
"rawOptions",
".",
"parser",
")",
"{",
"throw",
"new",
"UndefinedParserError",
"(",
"`",
"${",
"rawOptions",
".",
"filepath",
"}",
"`",
")",
";",
"}",
"}",
"}",
"const",
"parser",
"=",
"resolveParser",
"(",
"normalizer",
".",
"normalizeApiOptions",
"(",
"rawOptions",
",",
"[",
"supportOptions",
".",
"find",
"(",
"x",
"=>",
"x",
".",
"name",
"===",
"\"parser\"",
")",
"]",
",",
"{",
"passThrough",
":",
"true",
",",
"logger",
":",
"false",
"}",
")",
")",
";",
"rawOptions",
".",
"astFormat",
"=",
"parser",
".",
"astFormat",
";",
"rawOptions",
".",
"locEnd",
"=",
"parser",
".",
"locEnd",
";",
"rawOptions",
".",
"locStart",
"=",
"parser",
".",
"locStart",
";",
"const",
"plugin",
"=",
"getPlugin",
"(",
"rawOptions",
")",
";",
"rawOptions",
".",
"printer",
"=",
"plugin",
".",
"printers",
"[",
"rawOptions",
".",
"astFormat",
"]",
";",
"const",
"pluginDefaults",
"=",
"supportOptions",
".",
"filter",
"(",
"optionInfo",
"=>",
"optionInfo",
".",
"pluginDefaults",
"&&",
"optionInfo",
".",
"pluginDefaults",
"[",
"plugin",
".",
"name",
"]",
")",
".",
"reduce",
"(",
"(",
"reduced",
",",
"optionInfo",
")",
"=>",
"Object",
".",
"assign",
"(",
"reduced",
",",
"{",
"[",
"optionInfo",
".",
"name",
"]",
":",
"optionInfo",
".",
"pluginDefaults",
"[",
"plugin",
".",
"name",
"]",
"}",
")",
",",
"{",
"}",
")",
";",
"const",
"mixedDefaults",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaults",
",",
"pluginDefaults",
")",
";",
"Object",
".",
"keys",
"(",
"mixedDefaults",
")",
".",
"forEach",
"(",
"k",
"=>",
"{",
"if",
"(",
"rawOptions",
"[",
"k",
"]",
"==",
"null",
")",
"{",
"rawOptions",
"[",
"k",
"]",
"=",
"mixedDefaults",
"[",
"k",
"]",
";",
"}",
"}",
")",
";",
"if",
"(",
"rawOptions",
".",
"parser",
"===",
"\"json\"",
")",
"{",
"rawOptions",
".",
"trailingComma",
"=",
"\"none\"",
";",
"}",
"return",
"normalizer",
".",
"normalizeApiOptions",
"(",
"rawOptions",
",",
"supportOptions",
",",
"Object",
".",
"assign",
"(",
"{",
"passThrough",
":",
"Object",
".",
"keys",
"(",
"hiddenDefaults",
")",
"}",
",",
"opts",
")",
")",
";",
"}"
] | Copy options and fill in default values. | [
"Copy",
"options",
"and",
"fill",
"in",
"default",
"values",
"."
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/main/options.js#L20-L101 |
21,854 | josephfrazier/prettier_d | src/language-js/printer-estree.js | hasNgSideEffect | function hasNgSideEffect(path) {
return hasNode(path.getValue(), node => {
switch (node.type) {
case undefined:
return false;
case "CallExpression":
case "OptionalCallExpression":
case "AssignmentExpression":
return true;
}
});
} | javascript | function hasNgSideEffect(path) {
return hasNode(path.getValue(), node => {
switch (node.type) {
case undefined:
return false;
case "CallExpression":
case "OptionalCallExpression":
case "AssignmentExpression":
return true;
}
});
} | [
"function",
"hasNgSideEffect",
"(",
"path",
")",
"{",
"return",
"hasNode",
"(",
"path",
".",
"getValue",
"(",
")",
",",
"node",
"=>",
"{",
"switch",
"(",
"node",
".",
"type",
")",
"{",
"case",
"undefined",
":",
"return",
"false",
";",
"case",
"\"CallExpression\"",
":",
"case",
"\"OptionalCallExpression\"",
":",
"case",
"\"AssignmentExpression\"",
":",
"return",
"true",
";",
"}",
"}",
")",
";",
"}"
] | identify if an angular expression seems to have side effects | [
"identify",
"if",
"an",
"angular",
"expression",
"seems",
"to",
"have",
"side",
"effects"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/printer-estree.js#L3603-L3614 |
21,855 | josephfrazier/prettier_d | src/language-js/printer-estree.js | isMeaningfulJSXText | function isMeaningfulJSXText(node) {
return (
isLiteral(node) &&
(containsNonJsxWhitespaceRegex.test(rawText(node)) ||
!/\n/.test(rawText(node)))
);
} | javascript | function isMeaningfulJSXText(node) {
return (
isLiteral(node) &&
(containsNonJsxWhitespaceRegex.test(rawText(node)) ||
!/\n/.test(rawText(node)))
);
} | [
"function",
"isMeaningfulJSXText",
"(",
"node",
")",
"{",
"return",
"(",
"isLiteral",
"(",
"node",
")",
"&&",
"(",
"containsNonJsxWhitespaceRegex",
".",
"test",
"(",
"rawText",
"(",
"node",
")",
")",
"||",
"!",
"/",
"\\n",
"/",
".",
"test",
"(",
"rawText",
"(",
"node",
")",
")",
")",
")",
";",
"}"
] | Meaningful if it contains non-whitespace characters, or it contains whitespace without a new line. | [
"Meaningful",
"if",
"it",
"contains",
"non",
"-",
"whitespace",
"characters",
"or",
"it",
"contains",
"whitespace",
"without",
"a",
"new",
"line",
"."
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/printer-estree.js#L5059-L5065 |
21,856 | josephfrazier/prettier_d | src/language-markdown/utils.js | splitText | function splitText(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
const nodes = [];
(options.proseWrap === "preserve"
? text
: text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")
)
.split(/([ \t\n]+)/)
.forEach((token, index, tokens) => {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
}
// word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token
.split(new RegExp(`(${cjkPattern})`))
.forEach((innerToken, innerIndex, innerTokens) => {
if (
(innerIndex === 0 || innerIndex === innerTokens.length - 1) &&
innerToken === ""
) {
return;
}
// non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(
getLast(innerToken)
)
});
}
return;
}
// CJK character
appendNode(
punctuationRegex.test(innerToken)
? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
}
: {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken)
? KIND_K_LETTER
: KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
}
);
});
});
return nodes;
function appendNode(node) {
const lastNode = getLast(nodes);
if (lastNode && lastNode.type === "word") {
if (
(lastNode.kind === KIND_NON_CJK &&
node.kind === KIND_CJ_LETTER &&
!lastNode.hasTrailingPunctuation) ||
(lastNode.kind === KIND_CJ_LETTER &&
node.kind === KIND_NON_CJK &&
!node.hasLeadingPunctuation)
) {
nodes.push({ type: "whitespace", value: " " });
} else if (
!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) &&
// disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(value => /\u3000/.test(value))
) {
nodes.push({ type: "whitespace", value: "" });
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return (
(lastNode.kind === kind1 && node.kind === kind2) ||
(lastNode.kind === kind2 && node.kind === kind1)
);
}
}
} | javascript | function splitText(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
const nodes = [];
(options.proseWrap === "preserve"
? text
: text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")
)
.split(/([ \t\n]+)/)
.forEach((token, index, tokens) => {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
}
// word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token
.split(new RegExp(`(${cjkPattern})`))
.forEach((innerToken, innerIndex, innerTokens) => {
if (
(innerIndex === 0 || innerIndex === innerTokens.length - 1) &&
innerToken === ""
) {
return;
}
// non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(
getLast(innerToken)
)
});
}
return;
}
// CJK character
appendNode(
punctuationRegex.test(innerToken)
? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
}
: {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken)
? KIND_K_LETTER
: KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
}
);
});
});
return nodes;
function appendNode(node) {
const lastNode = getLast(nodes);
if (lastNode && lastNode.type === "word") {
if (
(lastNode.kind === KIND_NON_CJK &&
node.kind === KIND_CJ_LETTER &&
!lastNode.hasTrailingPunctuation) ||
(lastNode.kind === KIND_CJ_LETTER &&
node.kind === KIND_NON_CJK &&
!node.hasLeadingPunctuation)
) {
nodes.push({ type: "whitespace", value: " " });
} else if (
!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) &&
// disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(value => /\u3000/.test(value))
) {
nodes.push({ type: "whitespace", value: "" });
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return (
(lastNode.kind === kind1 && node.kind === kind2) ||
(lastNode.kind === kind2 && node.kind === kind1)
);
}
}
} | [
"function",
"splitText",
"(",
"text",
",",
"options",
")",
"{",
"const",
"KIND_NON_CJK",
"=",
"\"non-cjk\"",
";",
"const",
"KIND_CJ_LETTER",
"=",
"\"cj-letter\"",
";",
"const",
"KIND_K_LETTER",
"=",
"\"k-letter\"",
";",
"const",
"KIND_CJK_PUNCTUATION",
"=",
"\"cjk-punctuation\"",
";",
"const",
"nodes",
"=",
"[",
"]",
";",
"(",
"options",
".",
"proseWrap",
"===",
"\"preserve\"",
"?",
"text",
":",
"text",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"`",
"${",
"cjkPattern",
"}",
"\\n",
"${",
"cjkPattern",
"}",
"`",
",",
"\"g\"",
")",
",",
"\"$1$2\"",
")",
")",
".",
"split",
"(",
"/",
"([ \\t\\n]+)",
"/",
")",
".",
"forEach",
"(",
"(",
"token",
",",
"index",
",",
"tokens",
")",
"=>",
"{",
"// whitespace",
"if",
"(",
"index",
"%",
"2",
"===",
"1",
")",
"{",
"nodes",
".",
"push",
"(",
"{",
"type",
":",
"\"whitespace\"",
",",
"value",
":",
"/",
"\\n",
"/",
".",
"test",
"(",
"token",
")",
"?",
"\"\\n\"",
":",
"\" \"",
"}",
")",
";",
"return",
";",
"}",
"// word separated by whitespace",
"if",
"(",
"(",
"index",
"===",
"0",
"||",
"index",
"===",
"tokens",
".",
"length",
"-",
"1",
")",
"&&",
"token",
"===",
"\"\"",
")",
"{",
"return",
";",
"}",
"token",
".",
"split",
"(",
"new",
"RegExp",
"(",
"`",
"${",
"cjkPattern",
"}",
"`",
")",
")",
".",
"forEach",
"(",
"(",
"innerToken",
",",
"innerIndex",
",",
"innerTokens",
")",
"=>",
"{",
"if",
"(",
"(",
"innerIndex",
"===",
"0",
"||",
"innerIndex",
"===",
"innerTokens",
".",
"length",
"-",
"1",
")",
"&&",
"innerToken",
"===",
"\"\"",
")",
"{",
"return",
";",
"}",
"// non-CJK word",
"if",
"(",
"innerIndex",
"%",
"2",
"===",
"0",
")",
"{",
"if",
"(",
"innerToken",
"!==",
"\"\"",
")",
"{",
"appendNode",
"(",
"{",
"type",
":",
"\"word\"",
",",
"value",
":",
"innerToken",
",",
"kind",
":",
"KIND_NON_CJK",
",",
"hasLeadingPunctuation",
":",
"punctuationRegex",
".",
"test",
"(",
"innerToken",
"[",
"0",
"]",
")",
",",
"hasTrailingPunctuation",
":",
"punctuationRegex",
".",
"test",
"(",
"getLast",
"(",
"innerToken",
")",
")",
"}",
")",
";",
"}",
"return",
";",
"}",
"// CJK character",
"appendNode",
"(",
"punctuationRegex",
".",
"test",
"(",
"innerToken",
")",
"?",
"{",
"type",
":",
"\"word\"",
",",
"value",
":",
"innerToken",
",",
"kind",
":",
"KIND_CJK_PUNCTUATION",
",",
"hasLeadingPunctuation",
":",
"true",
",",
"hasTrailingPunctuation",
":",
"true",
"}",
":",
"{",
"type",
":",
"\"word\"",
",",
"value",
":",
"innerToken",
",",
"kind",
":",
"kRegex",
".",
"test",
"(",
"innerToken",
")",
"?",
"KIND_K_LETTER",
":",
"KIND_CJ_LETTER",
",",
"hasLeadingPunctuation",
":",
"false",
",",
"hasTrailingPunctuation",
":",
"false",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"nodes",
";",
"function",
"appendNode",
"(",
"node",
")",
"{",
"const",
"lastNode",
"=",
"getLast",
"(",
"nodes",
")",
";",
"if",
"(",
"lastNode",
"&&",
"lastNode",
".",
"type",
"===",
"\"word\"",
")",
"{",
"if",
"(",
"(",
"lastNode",
".",
"kind",
"===",
"KIND_NON_CJK",
"&&",
"node",
".",
"kind",
"===",
"KIND_CJ_LETTER",
"&&",
"!",
"lastNode",
".",
"hasTrailingPunctuation",
")",
"||",
"(",
"lastNode",
".",
"kind",
"===",
"KIND_CJ_LETTER",
"&&",
"node",
".",
"kind",
"===",
"KIND_NON_CJK",
"&&",
"!",
"node",
".",
"hasLeadingPunctuation",
")",
")",
"{",
"nodes",
".",
"push",
"(",
"{",
"type",
":",
"\"whitespace\"",
",",
"value",
":",
"\" \"",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"isBetween",
"(",
"KIND_NON_CJK",
",",
"KIND_CJK_PUNCTUATION",
")",
"&&",
"// disallow leading/trailing full-width whitespace",
"!",
"[",
"lastNode",
".",
"value",
",",
"node",
".",
"value",
"]",
".",
"some",
"(",
"value",
"=>",
"/",
"\\u3000",
"/",
".",
"test",
"(",
"value",
")",
")",
")",
"{",
"nodes",
".",
"push",
"(",
"{",
"type",
":",
"\"whitespace\"",
",",
"value",
":",
"\"\"",
"}",
")",
";",
"}",
"}",
"nodes",
".",
"push",
"(",
"node",
")",
";",
"function",
"isBetween",
"(",
"kind1",
",",
"kind2",
")",
"{",
"return",
"(",
"(",
"lastNode",
".",
"kind",
"===",
"kind1",
"&&",
"node",
".",
"kind",
"===",
"kind2",
")",
"||",
"(",
"lastNode",
".",
"kind",
"===",
"kind2",
"&&",
"node",
".",
"kind",
"===",
"kind1",
")",
")",
";",
"}",
"}",
"}"
] | split text into whitespaces and words
@param {string} text
@return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} | [
"split",
"text",
"into",
"whitespaces",
"and",
"words"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-markdown/utils.js#L43-L152 |
21,857 | josephfrazier/prettier_d | src/language-html/preprocess.js | extractWhitespaces | function extractWhitespaces(ast /*, options*/) {
const TYPE_WHITESPACE = "whitespace";
return ast.map(node => {
if (!node.children) {
return node;
}
if (
node.children.length === 0 ||
(node.children.length === 1 &&
node.children[0].type === "text" &&
node.children[0].value.trim().length === 0)
) {
return node.clone({
children: [],
hasDanglingSpaces: node.children.length !== 0
});
}
const isWhitespaceSensitive = isWhitespaceSensitiveNode(node);
const isIndentationSensitive = isIndentationSensitiveNode(node);
return node.clone({
isWhitespaceSensitive,
isIndentationSensitive,
children: node.children
// extract whitespace nodes
.reduce((newChildren, child) => {
if (child.type !== "text" || isWhitespaceSensitive) {
return newChildren.concat(child);
}
const localChildren = [];
const [, leadingSpaces, text, trailingSpaces] = child.value.match(
/^(\s*)([\s\S]*?)(\s*)$/
);
if (leadingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
const ParseSourceSpan = child.sourceSpan.constructor;
if (text) {
localChildren.push({
type: "text",
value: text,
sourceSpan: new ParseSourceSpan(
child.sourceSpan.start.moveBy(leadingSpaces.length),
child.sourceSpan.end.moveBy(-trailingSpaces.length)
)
});
}
if (trailingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
return newChildren.concat(localChildren);
}, [])
// set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
.reduce((newChildren, child, i, children) => {
if (child.type === TYPE_WHITESPACE) {
return newChildren;
}
const hasLeadingSpaces =
i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
const hasTrailingSpaces =
i !== children.length - 1 &&
children[i + 1].type === TYPE_WHITESPACE;
return newChildren.concat(
Object.assign({}, child, {
hasLeadingSpaces,
hasTrailingSpaces
})
);
}, [])
});
});
} | javascript | function extractWhitespaces(ast /*, options*/) {
const TYPE_WHITESPACE = "whitespace";
return ast.map(node => {
if (!node.children) {
return node;
}
if (
node.children.length === 0 ||
(node.children.length === 1 &&
node.children[0].type === "text" &&
node.children[0].value.trim().length === 0)
) {
return node.clone({
children: [],
hasDanglingSpaces: node.children.length !== 0
});
}
const isWhitespaceSensitive = isWhitespaceSensitiveNode(node);
const isIndentationSensitive = isIndentationSensitiveNode(node);
return node.clone({
isWhitespaceSensitive,
isIndentationSensitive,
children: node.children
// extract whitespace nodes
.reduce((newChildren, child) => {
if (child.type !== "text" || isWhitespaceSensitive) {
return newChildren.concat(child);
}
const localChildren = [];
const [, leadingSpaces, text, trailingSpaces] = child.value.match(
/^(\s*)([\s\S]*?)(\s*)$/
);
if (leadingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
const ParseSourceSpan = child.sourceSpan.constructor;
if (text) {
localChildren.push({
type: "text",
value: text,
sourceSpan: new ParseSourceSpan(
child.sourceSpan.start.moveBy(leadingSpaces.length),
child.sourceSpan.end.moveBy(-trailingSpaces.length)
)
});
}
if (trailingSpaces) {
localChildren.push({ type: TYPE_WHITESPACE });
}
return newChildren.concat(localChildren);
}, [])
// set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
.reduce((newChildren, child, i, children) => {
if (child.type === TYPE_WHITESPACE) {
return newChildren;
}
const hasLeadingSpaces =
i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
const hasTrailingSpaces =
i !== children.length - 1 &&
children[i + 1].type === TYPE_WHITESPACE;
return newChildren.concat(
Object.assign({}, child, {
hasLeadingSpaces,
hasTrailingSpaces
})
);
}, [])
});
});
} | [
"function",
"extractWhitespaces",
"(",
"ast",
"/*, options*/",
")",
"{",
"const",
"TYPE_WHITESPACE",
"=",
"\"whitespace\"",
";",
"return",
"ast",
".",
"map",
"(",
"node",
"=>",
"{",
"if",
"(",
"!",
"node",
".",
"children",
")",
"{",
"return",
"node",
";",
"}",
"if",
"(",
"node",
".",
"children",
".",
"length",
"===",
"0",
"||",
"(",
"node",
".",
"children",
".",
"length",
"===",
"1",
"&&",
"node",
".",
"children",
"[",
"0",
"]",
".",
"type",
"===",
"\"text\"",
"&&",
"node",
".",
"children",
"[",
"0",
"]",
".",
"value",
".",
"trim",
"(",
")",
".",
"length",
"===",
"0",
")",
")",
"{",
"return",
"node",
".",
"clone",
"(",
"{",
"children",
":",
"[",
"]",
",",
"hasDanglingSpaces",
":",
"node",
".",
"children",
".",
"length",
"!==",
"0",
"}",
")",
";",
"}",
"const",
"isWhitespaceSensitive",
"=",
"isWhitespaceSensitiveNode",
"(",
"node",
")",
";",
"const",
"isIndentationSensitive",
"=",
"isIndentationSensitiveNode",
"(",
"node",
")",
";",
"return",
"node",
".",
"clone",
"(",
"{",
"isWhitespaceSensitive",
",",
"isIndentationSensitive",
",",
"children",
":",
"node",
".",
"children",
"// extract whitespace nodes",
".",
"reduce",
"(",
"(",
"newChildren",
",",
"child",
")",
"=>",
"{",
"if",
"(",
"child",
".",
"type",
"!==",
"\"text\"",
"||",
"isWhitespaceSensitive",
")",
"{",
"return",
"newChildren",
".",
"concat",
"(",
"child",
")",
";",
"}",
"const",
"localChildren",
"=",
"[",
"]",
";",
"const",
"[",
",",
"leadingSpaces",
",",
"text",
",",
"trailingSpaces",
"]",
"=",
"child",
".",
"value",
".",
"match",
"(",
"/",
"^(\\s*)([\\s\\S]*?)(\\s*)$",
"/",
")",
";",
"if",
"(",
"leadingSpaces",
")",
"{",
"localChildren",
".",
"push",
"(",
"{",
"type",
":",
"TYPE_WHITESPACE",
"}",
")",
";",
"}",
"const",
"ParseSourceSpan",
"=",
"child",
".",
"sourceSpan",
".",
"constructor",
";",
"if",
"(",
"text",
")",
"{",
"localChildren",
".",
"push",
"(",
"{",
"type",
":",
"\"text\"",
",",
"value",
":",
"text",
",",
"sourceSpan",
":",
"new",
"ParseSourceSpan",
"(",
"child",
".",
"sourceSpan",
".",
"start",
".",
"moveBy",
"(",
"leadingSpaces",
".",
"length",
")",
",",
"child",
".",
"sourceSpan",
".",
"end",
".",
"moveBy",
"(",
"-",
"trailingSpaces",
".",
"length",
")",
")",
"}",
")",
";",
"}",
"if",
"(",
"trailingSpaces",
")",
"{",
"localChildren",
".",
"push",
"(",
"{",
"type",
":",
"TYPE_WHITESPACE",
"}",
")",
";",
"}",
"return",
"newChildren",
".",
"concat",
"(",
"localChildren",
")",
";",
"}",
",",
"[",
"]",
")",
"// set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes",
".",
"reduce",
"(",
"(",
"newChildren",
",",
"child",
",",
"i",
",",
"children",
")",
"=>",
"{",
"if",
"(",
"child",
".",
"type",
"===",
"TYPE_WHITESPACE",
")",
"{",
"return",
"newChildren",
";",
"}",
"const",
"hasLeadingSpaces",
"=",
"i",
"!==",
"0",
"&&",
"children",
"[",
"i",
"-",
"1",
"]",
".",
"type",
"===",
"TYPE_WHITESPACE",
";",
"const",
"hasTrailingSpaces",
"=",
"i",
"!==",
"children",
".",
"length",
"-",
"1",
"&&",
"children",
"[",
"i",
"+",
"1",
"]",
".",
"type",
"===",
"TYPE_WHITESPACE",
";",
"return",
"newChildren",
".",
"concat",
"(",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"child",
",",
"{",
"hasLeadingSpaces",
",",
"hasTrailingSpaces",
"}",
")",
")",
";",
"}",
",",
"[",
"]",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] | - add `hasLeadingSpaces` field
- add `hasTrailingSpaces` field
- add `hasDanglingSpaces` field for parent nodes
- add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
- remove insensitive whitespaces | [
"-",
"add",
"hasLeadingSpaces",
"field",
"-",
"add",
"hasTrailingSpaces",
"field",
"-",
"add",
"hasDanglingSpaces",
"field",
"for",
"parent",
"nodes",
"-",
"add",
"isWhitespaceSensitive",
"isIndentationSensitive",
"field",
"for",
"text",
"nodes",
"-",
"remove",
"insensitive",
"whitespaces"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-html/preprocess.js#L308-L390 |
21,858 | josephfrazier/prettier_d | src/language-html/preprocess.js | addIsSpaceSensitive | function addIsSpaceSensitive(ast /*, options */) {
return ast.map(node => {
if (!node.children) {
return node;
}
if (node.children.length === 0) {
return node.clone({
isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode(node)
});
}
return node.clone({
children: node.children
.map(child => {
return Object.assign({}, child, {
isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child),
isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(child)
});
})
.map((child, index, children) =>
Object.assign({}, child, {
isLeadingSpaceSensitive:
index === 0
? child.isLeadingSpaceSensitive
: children[index - 1].isTrailingSpaceSensitive &&
child.isLeadingSpaceSensitive,
isTrailingSpaceSensitive:
index === children.length - 1
? child.isTrailingSpaceSensitive
: children[index + 1].isLeadingSpaceSensitive &&
child.isTrailingSpaceSensitive
})
)
});
});
} | javascript | function addIsSpaceSensitive(ast /*, options */) {
return ast.map(node => {
if (!node.children) {
return node;
}
if (node.children.length === 0) {
return node.clone({
isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode(node)
});
}
return node.clone({
children: node.children
.map(child => {
return Object.assign({}, child, {
isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child),
isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(child)
});
})
.map((child, index, children) =>
Object.assign({}, child, {
isLeadingSpaceSensitive:
index === 0
? child.isLeadingSpaceSensitive
: children[index - 1].isTrailingSpaceSensitive &&
child.isLeadingSpaceSensitive,
isTrailingSpaceSensitive:
index === children.length - 1
? child.isTrailingSpaceSensitive
: children[index + 1].isLeadingSpaceSensitive &&
child.isTrailingSpaceSensitive
})
)
});
});
} | [
"function",
"addIsSpaceSensitive",
"(",
"ast",
"/*, options */",
")",
"{",
"return",
"ast",
".",
"map",
"(",
"node",
"=>",
"{",
"if",
"(",
"!",
"node",
".",
"children",
")",
"{",
"return",
"node",
";",
"}",
"if",
"(",
"node",
".",
"children",
".",
"length",
"===",
"0",
")",
"{",
"return",
"node",
".",
"clone",
"(",
"{",
"isDanglingSpaceSensitive",
":",
"isDanglingSpaceSensitiveNode",
"(",
"node",
")",
"}",
")",
";",
"}",
"return",
"node",
".",
"clone",
"(",
"{",
"children",
":",
"node",
".",
"children",
".",
"map",
"(",
"child",
"=>",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"child",
",",
"{",
"isLeadingSpaceSensitive",
":",
"isLeadingSpaceSensitiveNode",
"(",
"child",
")",
",",
"isTrailingSpaceSensitive",
":",
"isTrailingSpaceSensitiveNode",
"(",
"child",
")",
"}",
")",
";",
"}",
")",
".",
"map",
"(",
"(",
"child",
",",
"index",
",",
"children",
")",
"=>",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"child",
",",
"{",
"isLeadingSpaceSensitive",
":",
"index",
"===",
"0",
"?",
"child",
".",
"isLeadingSpaceSensitive",
":",
"children",
"[",
"index",
"-",
"1",
"]",
".",
"isTrailingSpaceSensitive",
"&&",
"child",
".",
"isLeadingSpaceSensitive",
",",
"isTrailingSpaceSensitive",
":",
"index",
"===",
"children",
".",
"length",
"-",
"1",
"?",
"child",
".",
"isTrailingSpaceSensitive",
":",
"children",
"[",
"index",
"+",
"1",
"]",
".",
"isLeadingSpaceSensitive",
"&&",
"child",
".",
"isTrailingSpaceSensitive",
"}",
")",
")",
"}",
")",
";",
"}",
")",
";",
"}"
] | - add `isLeadingSpaceSensitive` field
- add `isTrailingSpaceSensitive` field
- add `isDanglingSpaceSensitive` field for parent nodes | [
"-",
"add",
"isLeadingSpaceSensitive",
"field",
"-",
"add",
"isTrailingSpaceSensitive",
"field",
"-",
"add",
"isDanglingSpaceSensitive",
"field",
"for",
"parent",
"nodes"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-html/preprocess.js#L433-L469 |
21,859 | josephfrazier/prettier_d | src/language-html/utils.js | forceBreakContent | function forceBreakContent(node) {
return (
forceBreakChildren(node) ||
(node.type === "element" &&
node.children.length !== 0 &&
(["body", "template", "script", "style"].indexOf(node.name) !== -1 ||
node.children.some(child => hasNonTextChild(child)))) ||
(node.firstChild &&
node.firstChild === node.lastChild &&
(hasLeadingLineBreak(node.firstChild) &&
(!node.lastChild.isTrailingSpaceSensitive ||
hasTrailingLineBreak(node.lastChild))))
);
} | javascript | function forceBreakContent(node) {
return (
forceBreakChildren(node) ||
(node.type === "element" &&
node.children.length !== 0 &&
(["body", "template", "script", "style"].indexOf(node.name) !== -1 ||
node.children.some(child => hasNonTextChild(child)))) ||
(node.firstChild &&
node.firstChild === node.lastChild &&
(hasLeadingLineBreak(node.firstChild) &&
(!node.lastChild.isTrailingSpaceSensitive ||
hasTrailingLineBreak(node.lastChild))))
);
} | [
"function",
"forceBreakContent",
"(",
"node",
")",
"{",
"return",
"(",
"forceBreakChildren",
"(",
"node",
")",
"||",
"(",
"node",
".",
"type",
"===",
"\"element\"",
"&&",
"node",
".",
"children",
".",
"length",
"!==",
"0",
"&&",
"(",
"[",
"\"body\"",
",",
"\"template\"",
",",
"\"script\"",
",",
"\"style\"",
"]",
".",
"indexOf",
"(",
"node",
".",
"name",
")",
"!==",
"-",
"1",
"||",
"node",
".",
"children",
".",
"some",
"(",
"child",
"=>",
"hasNonTextChild",
"(",
"child",
")",
")",
")",
")",
"||",
"(",
"node",
".",
"firstChild",
"&&",
"node",
".",
"firstChild",
"===",
"node",
".",
"lastChild",
"&&",
"(",
"hasLeadingLineBreak",
"(",
"node",
".",
"firstChild",
")",
"&&",
"(",
"!",
"node",
".",
"lastChild",
".",
"isTrailingSpaceSensitive",
"||",
"hasTrailingLineBreak",
"(",
"node",
".",
"lastChild",
")",
")",
")",
")",
")",
";",
"}"
] | firstChild leadingSpaces and lastChild trailingSpaces | [
"firstChild",
"leadingSpaces",
"and",
"lastChild",
"trailingSpaces"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-html/utils.js#L270-L283 |
21,860 | josephfrazier/prettier_d | src/language-html/utils.js | forceBreakChildren | function forceBreakChildren(node) {
return (
node.type === "element" &&
node.children.length !== 0 &&
(["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 ||
(node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell"))
);
} | javascript | function forceBreakChildren(node) {
return (
node.type === "element" &&
node.children.length !== 0 &&
(["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 ||
(node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell"))
);
} | [
"function",
"forceBreakChildren",
"(",
"node",
")",
"{",
"return",
"(",
"node",
".",
"type",
"===",
"\"element\"",
"&&",
"node",
".",
"children",
".",
"length",
"!==",
"0",
"&&",
"(",
"[",
"\"html\"",
",",
"\"head\"",
",",
"\"ul\"",
",",
"\"ol\"",
",",
"\"select\"",
"]",
".",
"indexOf",
"(",
"node",
".",
"name",
")",
"!==",
"-",
"1",
"||",
"(",
"node",
".",
"cssDisplay",
".",
"startsWith",
"(",
"\"table\"",
")",
"&&",
"node",
".",
"cssDisplay",
"!==",
"\"table-cell\"",
")",
")",
")",
";",
"}"
] | spaces between children | [
"spaces",
"between",
"children"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-html/utils.js#L286-L293 |
21,861 | josephfrazier/prettier_d | src/language-js/embed.js | replacePlaceholders | function replacePlaceholders(quasisDoc, expressionDocs) {
if (!expressionDocs || !expressionDocs.length) {
return quasisDoc;
}
const expressions = expressionDocs.slice();
let replaceCounter = 0;
const newDoc = mapDoc(quasisDoc, doc => {
if (!doc || !doc.parts || !doc.parts.length) {
return doc;
}
let parts = doc.parts;
const atIndex = parts.indexOf("@");
const placeholderIndex = atIndex + 1;
if (
atIndex > -1 &&
typeof parts[placeholderIndex] === "string" &&
parts[placeholderIndex].startsWith("prettier-placeholder")
) {
// If placeholder is split, join it
const at = parts[atIndex];
const placeholder = parts[placeholderIndex];
const rest = parts.slice(placeholderIndex + 1);
parts = parts
.slice(0, atIndex)
.concat([at + placeholder])
.concat(rest);
}
const atPlaceholderIndex = parts.findIndex(
part =>
typeof part === "string" && part.startsWith("@prettier-placeholder")
);
if (atPlaceholderIndex > -1) {
const placeholder = parts[atPlaceholderIndex];
const rest = parts.slice(atPlaceholderIndex + 1);
const placeholderMatch = placeholder.match(
/@prettier-placeholder-(.+)-id([\s\S]*)/
);
const placeholderID = placeholderMatch[1];
// When the expression has a suffix appended, like:
// animation: linear ${time}s ease-out;
const suffix = placeholderMatch[2];
const expression = expressions[placeholderID];
replaceCounter++;
parts = parts
.slice(0, atPlaceholderIndex)
.concat(["${", expression, "}" + suffix])
.concat(rest);
}
return Object.assign({}, doc, {
parts: parts
});
});
return expressions.length === replaceCounter ? newDoc : null;
} | javascript | function replacePlaceholders(quasisDoc, expressionDocs) {
if (!expressionDocs || !expressionDocs.length) {
return quasisDoc;
}
const expressions = expressionDocs.slice();
let replaceCounter = 0;
const newDoc = mapDoc(quasisDoc, doc => {
if (!doc || !doc.parts || !doc.parts.length) {
return doc;
}
let parts = doc.parts;
const atIndex = parts.indexOf("@");
const placeholderIndex = atIndex + 1;
if (
atIndex > -1 &&
typeof parts[placeholderIndex] === "string" &&
parts[placeholderIndex].startsWith("prettier-placeholder")
) {
// If placeholder is split, join it
const at = parts[atIndex];
const placeholder = parts[placeholderIndex];
const rest = parts.slice(placeholderIndex + 1);
parts = parts
.slice(0, atIndex)
.concat([at + placeholder])
.concat(rest);
}
const atPlaceholderIndex = parts.findIndex(
part =>
typeof part === "string" && part.startsWith("@prettier-placeholder")
);
if (atPlaceholderIndex > -1) {
const placeholder = parts[atPlaceholderIndex];
const rest = parts.slice(atPlaceholderIndex + 1);
const placeholderMatch = placeholder.match(
/@prettier-placeholder-(.+)-id([\s\S]*)/
);
const placeholderID = placeholderMatch[1];
// When the expression has a suffix appended, like:
// animation: linear ${time}s ease-out;
const suffix = placeholderMatch[2];
const expression = expressions[placeholderID];
replaceCounter++;
parts = parts
.slice(0, atPlaceholderIndex)
.concat(["${", expression, "}" + suffix])
.concat(rest);
}
return Object.assign({}, doc, {
parts: parts
});
});
return expressions.length === replaceCounter ? newDoc : null;
} | [
"function",
"replacePlaceholders",
"(",
"quasisDoc",
",",
"expressionDocs",
")",
"{",
"if",
"(",
"!",
"expressionDocs",
"||",
"!",
"expressionDocs",
".",
"length",
")",
"{",
"return",
"quasisDoc",
";",
"}",
"const",
"expressions",
"=",
"expressionDocs",
".",
"slice",
"(",
")",
";",
"let",
"replaceCounter",
"=",
"0",
";",
"const",
"newDoc",
"=",
"mapDoc",
"(",
"quasisDoc",
",",
"doc",
"=>",
"{",
"if",
"(",
"!",
"doc",
"||",
"!",
"doc",
".",
"parts",
"||",
"!",
"doc",
".",
"parts",
".",
"length",
")",
"{",
"return",
"doc",
";",
"}",
"let",
"parts",
"=",
"doc",
".",
"parts",
";",
"const",
"atIndex",
"=",
"parts",
".",
"indexOf",
"(",
"\"@\"",
")",
";",
"const",
"placeholderIndex",
"=",
"atIndex",
"+",
"1",
";",
"if",
"(",
"atIndex",
">",
"-",
"1",
"&&",
"typeof",
"parts",
"[",
"placeholderIndex",
"]",
"===",
"\"string\"",
"&&",
"parts",
"[",
"placeholderIndex",
"]",
".",
"startsWith",
"(",
"\"prettier-placeholder\"",
")",
")",
"{",
"// If placeholder is split, join it",
"const",
"at",
"=",
"parts",
"[",
"atIndex",
"]",
";",
"const",
"placeholder",
"=",
"parts",
"[",
"placeholderIndex",
"]",
";",
"const",
"rest",
"=",
"parts",
".",
"slice",
"(",
"placeholderIndex",
"+",
"1",
")",
";",
"parts",
"=",
"parts",
".",
"slice",
"(",
"0",
",",
"atIndex",
")",
".",
"concat",
"(",
"[",
"at",
"+",
"placeholder",
"]",
")",
".",
"concat",
"(",
"rest",
")",
";",
"}",
"const",
"atPlaceholderIndex",
"=",
"parts",
".",
"findIndex",
"(",
"part",
"=>",
"typeof",
"part",
"===",
"\"string\"",
"&&",
"part",
".",
"startsWith",
"(",
"\"@prettier-placeholder\"",
")",
")",
";",
"if",
"(",
"atPlaceholderIndex",
">",
"-",
"1",
")",
"{",
"const",
"placeholder",
"=",
"parts",
"[",
"atPlaceholderIndex",
"]",
";",
"const",
"rest",
"=",
"parts",
".",
"slice",
"(",
"atPlaceholderIndex",
"+",
"1",
")",
";",
"const",
"placeholderMatch",
"=",
"placeholder",
".",
"match",
"(",
"/",
"@prettier-placeholder-(.+)-id([\\s\\S]*)",
"/",
")",
";",
"const",
"placeholderID",
"=",
"placeholderMatch",
"[",
"1",
"]",
";",
"// When the expression has a suffix appended, like:",
"// animation: linear ${time}s ease-out;",
"const",
"suffix",
"=",
"placeholderMatch",
"[",
"2",
"]",
";",
"const",
"expression",
"=",
"expressions",
"[",
"placeholderID",
"]",
";",
"replaceCounter",
"++",
";",
"parts",
"=",
"parts",
".",
"slice",
"(",
"0",
",",
"atPlaceholderIndex",
")",
".",
"concat",
"(",
"[",
"\"${\"",
",",
"expression",
",",
"\"}\"",
"+",
"suffix",
"]",
")",
".",
"concat",
"(",
"rest",
")",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"doc",
",",
"{",
"parts",
":",
"parts",
"}",
")",
";",
"}",
")",
";",
"return",
"expressions",
".",
"length",
"===",
"replaceCounter",
"?",
"newDoc",
":",
"null",
";",
"}"
] | Search all the placeholders in the quasisDoc tree and replace them with the expression docs one by one returns a new doc with all the placeholders replaced, or null if it couldn't replace any expression | [
"Search",
"all",
"the",
"placeholders",
"in",
"the",
"quasisDoc",
"tree",
"and",
"replace",
"them",
"with",
"the",
"expression",
"docs",
"one",
"by",
"one",
"returns",
"a",
"new",
"doc",
"with",
"all",
"the",
"placeholders",
"replaced",
"or",
"null",
"if",
"it",
"couldn",
"t",
"replace",
"any",
"expression"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/embed.js#L251-L307 |
21,862 | josephfrazier/prettier_d | src/language-js/embed.js | isStyledComponents | function isStyledComponents(path) {
const parent = path.getParentNode();
if (!parent || parent.type !== "TaggedTemplateExpression") {
return false;
}
const tag = parent.tag;
switch (tag.type) {
case "MemberExpression":
return (
// styled.foo``
isStyledIdentifier(tag.object) ||
// Component.extend``
isStyledExtend(tag)
);
case "CallExpression":
return (
// styled(Component)``
isStyledIdentifier(tag.callee) ||
(tag.callee.type === "MemberExpression" &&
((tag.callee.object.type === "MemberExpression" &&
// styled.foo.attr({})``
(isStyledIdentifier(tag.callee.object.object) ||
// Component.extend.attr({)``
isStyledExtend(tag.callee.object))) ||
// styled(Component).attr({})``
(tag.callee.object.type === "CallExpression" &&
isStyledIdentifier(tag.callee.object.callee))))
);
case "Identifier":
// css``
return tag.name === "css";
default:
return false;
}
} | javascript | function isStyledComponents(path) {
const parent = path.getParentNode();
if (!parent || parent.type !== "TaggedTemplateExpression") {
return false;
}
const tag = parent.tag;
switch (tag.type) {
case "MemberExpression":
return (
// styled.foo``
isStyledIdentifier(tag.object) ||
// Component.extend``
isStyledExtend(tag)
);
case "CallExpression":
return (
// styled(Component)``
isStyledIdentifier(tag.callee) ||
(tag.callee.type === "MemberExpression" &&
((tag.callee.object.type === "MemberExpression" &&
// styled.foo.attr({})``
(isStyledIdentifier(tag.callee.object.object) ||
// Component.extend.attr({)``
isStyledExtend(tag.callee.object))) ||
// styled(Component).attr({})``
(tag.callee.object.type === "CallExpression" &&
isStyledIdentifier(tag.callee.object.callee))))
);
case "Identifier":
// css``
return tag.name === "css";
default:
return false;
}
} | [
"function",
"isStyledComponents",
"(",
"path",
")",
"{",
"const",
"parent",
"=",
"path",
".",
"getParentNode",
"(",
")",
";",
"if",
"(",
"!",
"parent",
"||",
"parent",
".",
"type",
"!==",
"\"TaggedTemplateExpression\"",
")",
"{",
"return",
"false",
";",
"}",
"const",
"tag",
"=",
"parent",
".",
"tag",
";",
"switch",
"(",
"tag",
".",
"type",
")",
"{",
"case",
"\"MemberExpression\"",
":",
"return",
"(",
"// styled.foo``",
"isStyledIdentifier",
"(",
"tag",
".",
"object",
")",
"||",
"// Component.extend``",
"isStyledExtend",
"(",
"tag",
")",
")",
";",
"case",
"\"CallExpression\"",
":",
"return",
"(",
"// styled(Component)``",
"isStyledIdentifier",
"(",
"tag",
".",
"callee",
")",
"||",
"(",
"tag",
".",
"callee",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"(",
"(",
"tag",
".",
"callee",
".",
"object",
".",
"type",
"===",
"\"MemberExpression\"",
"&&",
"// styled.foo.attr({})``",
"(",
"isStyledIdentifier",
"(",
"tag",
".",
"callee",
".",
"object",
".",
"object",
")",
"||",
"// Component.extend.attr({)``",
"isStyledExtend",
"(",
"tag",
".",
"callee",
".",
"object",
")",
")",
")",
"||",
"// styled(Component).attr({})``",
"(",
"tag",
".",
"callee",
".",
"object",
".",
"type",
"===",
"\"CallExpression\"",
"&&",
"isStyledIdentifier",
"(",
"tag",
".",
"callee",
".",
"object",
".",
"callee",
")",
")",
")",
")",
")",
";",
"case",
"\"Identifier\"",
":",
"// css``",
"return",
"tag",
".",
"name",
"===",
"\"css\"",
";",
"default",
":",
"return",
"false",
";",
"}",
"}"
] | styled-components template literals | [
"styled",
"-",
"components",
"template",
"literals"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/embed.js#L413-L453 |
21,863 | josephfrazier/prettier_d | src/language-js/embed.js | isCssProp | function isCssProp(path) {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
parentParent &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXAttribute" &&
parentParent.name.type === "JSXIdentifier" &&
parentParent.name.name === "css"
);
} | javascript | function isCssProp(path) {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
return (
parentParent &&
parent.type === "JSXExpressionContainer" &&
parentParent.type === "JSXAttribute" &&
parentParent.name.type === "JSXIdentifier" &&
parentParent.name.name === "css"
);
} | [
"function",
"isCssProp",
"(",
"path",
")",
"{",
"const",
"parent",
"=",
"path",
".",
"getParentNode",
"(",
")",
";",
"const",
"parentParent",
"=",
"path",
".",
"getParentNode",
"(",
"1",
")",
";",
"return",
"(",
"parentParent",
"&&",
"parent",
".",
"type",
"===",
"\"JSXExpressionContainer\"",
"&&",
"parentParent",
".",
"type",
"===",
"\"JSXAttribute\"",
"&&",
"parentParent",
".",
"name",
".",
"type",
"===",
"\"JSXIdentifier\"",
"&&",
"parentParent",
".",
"name",
".",
"name",
"===",
"\"css\"",
")",
";",
"}"
] | JSX element with CSS prop | [
"JSX",
"element",
"with",
"CSS",
"prop"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/embed.js#L458-L468 |
21,864 | josephfrazier/prettier_d | src/language-js/embed.js | isHtml | function isHtml(path) {
const node = path.getValue();
return (
hasLanguageComment(node, "HTML") ||
isPathMatch(path, [
node => node.type === "TemplateLiteral",
(node, name) =>
node.type === "TaggedTemplateExpression" &&
node.tag.type === "Identifier" &&
node.tag.name === "html" &&
name === "quasi"
])
);
} | javascript | function isHtml(path) {
const node = path.getValue();
return (
hasLanguageComment(node, "HTML") ||
isPathMatch(path, [
node => node.type === "TemplateLiteral",
(node, name) =>
node.type === "TaggedTemplateExpression" &&
node.tag.type === "Identifier" &&
node.tag.name === "html" &&
name === "quasi"
])
);
} | [
"function",
"isHtml",
"(",
"path",
")",
"{",
"const",
"node",
"=",
"path",
".",
"getValue",
"(",
")",
";",
"return",
"(",
"hasLanguageComment",
"(",
"node",
",",
"\"HTML\"",
")",
"||",
"isPathMatch",
"(",
"path",
",",
"[",
"node",
"=>",
"node",
".",
"type",
"===",
"\"TemplateLiteral\"",
",",
"(",
"node",
",",
"name",
")",
"=>",
"node",
".",
"type",
"===",
"\"TaggedTemplateExpression\"",
"&&",
"node",
".",
"tag",
".",
"type",
"===",
"\"Identifier\"",
"&&",
"node",
".",
"tag",
".",
"name",
"===",
"\"html\"",
"&&",
"name",
"===",
"\"quasi\"",
"]",
")",
")",
";",
"}"
] | - html`...`
- HTML comment block | [
"-",
"html",
"...",
"-",
"HTML",
"comment",
"block"
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/src/language-js/embed.js#L551-L564 |
21,865 | josephfrazier/prettier_d | scripts/release/steps/post-publish-steps.js | checkSchema | async function checkSchema() {
const schema = await execa.stdout("node", ["scripts/generate-schema.js"]);
const remoteSchema = await logPromise(
"Checking current schema in SchemaStore",
fetch(RAW_URL)
.then(r => r.text())
.then(t => t.trim())
);
if (schema === remoteSchema) {
return;
}
return dedent(chalk`
{bold.underline The schema in {yellow SchemaStore} needs an update.}
- Open {cyan.underline ${EDIT_URL}}
- Run {yellow node scripts/generate-schema.js} and copy the new schema
- Paste it on GitHub interface
- Open a PR
`);
} | javascript | async function checkSchema() {
const schema = await execa.stdout("node", ["scripts/generate-schema.js"]);
const remoteSchema = await logPromise(
"Checking current schema in SchemaStore",
fetch(RAW_URL)
.then(r => r.text())
.then(t => t.trim())
);
if (schema === remoteSchema) {
return;
}
return dedent(chalk`
{bold.underline The schema in {yellow SchemaStore} needs an update.}
- Open {cyan.underline ${EDIT_URL}}
- Run {yellow node scripts/generate-schema.js} and copy the new schema
- Paste it on GitHub interface
- Open a PR
`);
} | [
"async",
"function",
"checkSchema",
"(",
")",
"{",
"const",
"schema",
"=",
"await",
"execa",
".",
"stdout",
"(",
"\"node\"",
",",
"[",
"\"scripts/generate-schema.js\"",
"]",
")",
";",
"const",
"remoteSchema",
"=",
"await",
"logPromise",
"(",
"\"Checking current schema in SchemaStore\"",
",",
"fetch",
"(",
"RAW_URL",
")",
".",
"then",
"(",
"r",
"=>",
"r",
".",
"text",
"(",
")",
")",
".",
"then",
"(",
"t",
"=>",
"t",
".",
"trim",
"(",
")",
")",
")",
";",
"if",
"(",
"schema",
"===",
"remoteSchema",
")",
"{",
"return",
";",
"}",
"return",
"dedent",
"(",
"chalk",
"`",
"${",
"EDIT_URL",
"}",
"`",
")",
";",
"}"
] | Any optional or manual step can be warned in this script. | [
"Any",
"optional",
"or",
"manual",
"step",
"can",
"be",
"warned",
"in",
"this",
"script",
"."
] | f45912afe811b53cc865b2e6c147218fd40f4ed9 | https://github.com/josephfrazier/prettier_d/blob/f45912afe811b53cc865b2e6c147218fd40f4ed9/scripts/release/steps/post-publish-steps.js#L16-L36 |
21,866 | nodejitsu/haibu | lib/haibu/common/npm.js | installAll | function installAll(deps) {
npm.commands.install(dir, deps, function (err) {
if (err) {
return callback(err);
}
haibu.emit('npm:install:success', 'info', meta);
callback(null, deps);
});
} | javascript | function installAll(deps) {
npm.commands.install(dir, deps, function (err) {
if (err) {
return callback(err);
}
haibu.emit('npm:install:success', 'info', meta);
callback(null, deps);
});
} | [
"function",
"installAll",
"(",
"deps",
")",
"{",
"npm",
".",
"commands",
".",
"install",
"(",
"dir",
",",
"deps",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"haibu",
".",
"emit",
"(",
"'npm:install:success'",
",",
"'info'",
",",
"meta",
")",
";",
"callback",
"(",
"null",
",",
"deps",
")",
";",
"}",
")",
";",
"}"
] | Install all dependencies into the target directory | [
"Install",
"all",
"dependencies",
"into",
"the",
"target",
"directory"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/common/npm.js#L118-L127 |
21,867 | nodejitsu/haibu | lib/haibu/common/npm.js | loadAndInstall | function loadAndInstall() {
meta = { packages: target };
exports.load(function (err) {
if (err) {
return callback(err);
}
installAll(target);
});
} | javascript | function loadAndInstall() {
meta = { packages: target };
exports.load(function (err) {
if (err) {
return callback(err);
}
installAll(target);
});
} | [
"function",
"loadAndInstall",
"(",
")",
"{",
"meta",
"=",
"{",
"packages",
":",
"target",
"}",
";",
"exports",
".",
"load",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"installAll",
"(",
"target",
")",
";",
"}",
")",
";",
"}"
] | Load npm and install the raw list of dependencies | [
"Load",
"npm",
"and",
"install",
"the",
"raw",
"list",
"of",
"dependencies"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/common/npm.js#L155-L164 |
21,868 | nodejitsu/haibu | lib/haibu/drone/drone.js | onError | function onError(err) {
err.usage = 'tar -cvz . | curl -sSNT- HOST/deploy/USER/APP';
err.blame = {
type: 'system',
message: 'Unable to unpack tarball'
};
return callback(err);
} | javascript | function onError(err) {
err.usage = 'tar -cvz . | curl -sSNT- HOST/deploy/USER/APP';
err.blame = {
type: 'system',
message: 'Unable to unpack tarball'
};
return callback(err);
} | [
"function",
"onError",
"(",
"err",
")",
"{",
"err",
".",
"usage",
"=",
"'tar -cvz . | curl -sSNT- HOST/deploy/USER/APP'",
";",
"err",
".",
"blame",
"=",
"{",
"type",
":",
"'system'",
",",
"message",
":",
"'Unable to unpack tarball'",
"}",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}"
] | Handle error caused by `zlib.Gunzip` or `tar.Extract` failure | [
"Handle",
"error",
"caused",
"by",
"zlib",
".",
"Gunzip",
"or",
"tar",
".",
"Extract",
"failure"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/drone/drone.js#L85-L92 |
21,869 | nodejitsu/haibu | lib/haibu/core/spawner.js | onStdout | function onStdout (data) {
data = data.toString();
haibu.emit('drone:stdout', 'info', data, meta);
if (!responded) {
stdout = stdout.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
} | javascript | function onStdout (data) {
data = data.toString();
haibu.emit('drone:stdout', 'info', data, meta);
if (!responded) {
stdout = stdout.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
} | [
"function",
"onStdout",
"(",
"data",
")",
"{",
"data",
"=",
"data",
".",
"toString",
"(",
")",
";",
"haibu",
".",
"emit",
"(",
"'drone:stdout'",
",",
"'info'",
",",
"data",
",",
"meta",
")",
";",
"if",
"(",
"!",
"responded",
")",
"{",
"stdout",
"=",
"stdout",
".",
"concat",
"(",
"data",
".",
"split",
"(",
"'\\n'",
")",
".",
"filter",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"line",
".",
"length",
">",
"0",
"}",
")",
")",
";",
"}",
"}"
] | Log data from `drone.stdout` to haibu | [
"Log",
"data",
"from",
"drone",
".",
"stdout",
"to",
"haibu"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L261-L268 |
21,870 | nodejitsu/haibu | lib/haibu/core/spawner.js | onStderr | function onStderr (data) {
data = data.toString();
haibu.emit('drone:stderr', 'error', data, meta);
if (!responded) {
stderr = stderr.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
} | javascript | function onStderr (data) {
data = data.toString();
haibu.emit('drone:stderr', 'error', data, meta);
if (!responded) {
stderr = stderr.concat(data.split('\n').filter(function (line) { return line.length > 0 }));
}
} | [
"function",
"onStderr",
"(",
"data",
")",
"{",
"data",
"=",
"data",
".",
"toString",
"(",
")",
";",
"haibu",
".",
"emit",
"(",
"'drone:stderr'",
",",
"'error'",
",",
"data",
",",
"meta",
")",
";",
"if",
"(",
"!",
"responded",
")",
"{",
"stderr",
"=",
"stderr",
".",
"concat",
"(",
"data",
".",
"split",
"(",
"'\\n'",
")",
".",
"filter",
"(",
"function",
"(",
"line",
")",
"{",
"return",
"line",
".",
"length",
">",
"0",
"}",
")",
")",
";",
"}",
"}"
] | Log data from `drone.stderr` to haibu | [
"Log",
"data",
"from",
"drone",
".",
"stderr",
"to",
"haibu"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L273-L280 |
21,871 | nodejitsu/haibu | lib/haibu/core/spawner.js | onCarapacePort | function onCarapacePort (info) {
if (!responded && info && info.event === 'port') {
responded = true;
result.socket = {
host: self.host,
port: info.data.port
};
drone.minUptime = 0;
haibu.emit('drone:port', 'info', {
pkg: app,
info: info
});
callback(null, result);
//
// Remove listeners to related events
//
drone.removeListener('exit', onExit);
drone.removeListener('error', onError);
clearTimeout(timeout);
}
} | javascript | function onCarapacePort (info) {
if (!responded && info && info.event === 'port') {
responded = true;
result.socket = {
host: self.host,
port: info.data.port
};
drone.minUptime = 0;
haibu.emit('drone:port', 'info', {
pkg: app,
info: info
});
callback(null, result);
//
// Remove listeners to related events
//
drone.removeListener('exit', onExit);
drone.removeListener('error', onError);
clearTimeout(timeout);
}
} | [
"function",
"onCarapacePort",
"(",
"info",
")",
"{",
"if",
"(",
"!",
"responded",
"&&",
"info",
"&&",
"info",
".",
"event",
"===",
"'port'",
")",
"{",
"responded",
"=",
"true",
";",
"result",
".",
"socket",
"=",
"{",
"host",
":",
"self",
".",
"host",
",",
"port",
":",
"info",
".",
"data",
".",
"port",
"}",
";",
"drone",
".",
"minUptime",
"=",
"0",
";",
"haibu",
".",
"emit",
"(",
"'drone:port'",
",",
"'info'",
",",
"{",
"pkg",
":",
"app",
",",
"info",
":",
"info",
"}",
")",
";",
"callback",
"(",
"null",
",",
"result",
")",
";",
"//",
"// Remove listeners to related events",
"//",
"drone",
".",
"removeListener",
"(",
"'exit'",
",",
"onExit",
")",
";",
"drone",
".",
"removeListener",
"(",
"'error'",
",",
"onError",
")",
";",
"clearTimeout",
"(",
"timeout",
")",
";",
"}",
"}"
] | When the carapace provides the port that the drone has bound to then respond to the callback | [
"When",
"the",
"carapace",
"provides",
"the",
"port",
"that",
"the",
"drone",
"has",
"bound",
"to",
"then",
"respond",
"to",
"the",
"callback"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L307-L331 |
21,872 | nodejitsu/haibu | lib/haibu/core/spawner.js | onChildStart | function onChildStart (monitor, data) {
result = {
monitor: monitor,
process: monitor.child,
data: data,
pid: monitor.childData.pid,
pkg: app
};
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
} | javascript | function onChildStart (monitor, data) {
result = {
monitor: monitor,
process: monitor.child,
data: data,
pid: monitor.childData.pid,
pkg: app
};
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
} | [
"function",
"onChildStart",
"(",
"monitor",
",",
"data",
")",
"{",
"result",
"=",
"{",
"monitor",
":",
"monitor",
",",
"process",
":",
"monitor",
".",
"child",
",",
"data",
":",
"data",
",",
"pid",
":",
"monitor",
".",
"childData",
".",
"pid",
",",
"pkg",
":",
"app",
"}",
";",
"haibu",
".",
"emit",
"(",
"[",
"'drone'",
",",
"'start'",
"]",
",",
"'info'",
",",
"{",
"process",
":",
"data",
",",
"pkg",
":",
"result",
".",
"pkg",
"}",
")",
";",
"}"
] | When the drone starts, update the result for monitoring software | [
"When",
"the",
"drone",
"starts",
"update",
"the",
"result",
"for",
"monitoring",
"software"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L336-L349 |
21,873 | nodejitsu/haibu | lib/haibu/core/spawner.js | onChildRestart | function onChildRestart (monitor, data) {
haibu.emit(['drone', 'stop'], 'info', {
process: result.data,
pkg: result.pkg
});
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
} | javascript | function onChildRestart (monitor, data) {
haibu.emit(['drone', 'stop'], 'info', {
process: result.data,
pkg: result.pkg
});
haibu.emit(['drone', 'start'], 'info', {
process: data,
pkg: result.pkg
});
} | [
"function",
"onChildRestart",
"(",
"monitor",
",",
"data",
")",
"{",
"haibu",
".",
"emit",
"(",
"[",
"'drone'",
",",
"'stop'",
"]",
",",
"'info'",
",",
"{",
"process",
":",
"result",
".",
"data",
",",
"pkg",
":",
"result",
".",
"pkg",
"}",
")",
";",
"haibu",
".",
"emit",
"(",
"[",
"'drone'",
",",
"'start'",
"]",
",",
"'info'",
",",
"{",
"process",
":",
"data",
",",
"pkg",
":",
"result",
".",
"pkg",
"}",
")",
";",
"}"
] | When the drone stops, update the result for monitoring software | [
"When",
"the",
"drone",
"stops",
"update",
"the",
"result",
"for",
"monitoring",
"software"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L354-L364 |
21,874 | nodejitsu/haibu | lib/haibu/core/spawner.js | onExit | function onExit () {
if (!responded) {
errState = true;
responded = true;
error = new Error('Error spawning drone');
error.blame = {
type: 'user',
message: 'Script prematurely exited'
}
error.stdout = stdout.join('\n');
error.stderr = stderr.join('\n');
callback(error);
//
// Remove listeners to related events.
//
drone.removeListener('error', onError);
drone.removeListener('message', onCarapacePort);
clearTimeout(timeout);
}
} | javascript | function onExit () {
if (!responded) {
errState = true;
responded = true;
error = new Error('Error spawning drone');
error.blame = {
type: 'user',
message: 'Script prematurely exited'
}
error.stdout = stdout.join('\n');
error.stderr = stderr.join('\n');
callback(error);
//
// Remove listeners to related events.
//
drone.removeListener('error', onError);
drone.removeListener('message', onCarapacePort);
clearTimeout(timeout);
}
} | [
"function",
"onExit",
"(",
")",
"{",
"if",
"(",
"!",
"responded",
")",
"{",
"errState",
"=",
"true",
";",
"responded",
"=",
"true",
";",
"error",
"=",
"new",
"Error",
"(",
"'Error spawning drone'",
")",
";",
"error",
".",
"blame",
"=",
"{",
"type",
":",
"'user'",
",",
"message",
":",
"'Script prematurely exited'",
"}",
"error",
".",
"stdout",
"=",
"stdout",
".",
"join",
"(",
"'\\n'",
")",
";",
"error",
".",
"stderr",
"=",
"stderr",
".",
"join",
"(",
"'\\n'",
")",
";",
"callback",
"(",
"error",
")",
";",
"//",
"// Remove listeners to related events.",
"//",
"drone",
".",
"removeListener",
"(",
"'error'",
",",
"onError",
")",
";",
"drone",
".",
"removeListener",
"(",
"'message'",
",",
"onCarapacePort",
")",
";",
"clearTimeout",
"(",
"timeout",
")",
";",
"}",
"}"
] | If the drone exits prematurely then respond with an error containing the data we receieved from `stderr` | [
"If",
"the",
"drone",
"exits",
"prematurely",
"then",
"respond",
"with",
"an",
"error",
"containing",
"the",
"data",
"we",
"receieved",
"from",
"stderr"
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/core/spawner.js#L370-L390 |
21,875 | nodejitsu/haibu | lib/haibu/drone/index.js | startDrones | function startDrones (pkg, done) {
if (pkg.drones == 0) {
return done();
}
var started = 0;
async.whilst(function () {
return started < pkg.drones;
}, function (next) {
started++;
server.drone.start(pkg, next);
}, done);
} | javascript | function startDrones (pkg, done) {
if (pkg.drones == 0) {
return done();
}
var started = 0;
async.whilst(function () {
return started < pkg.drones;
}, function (next) {
started++;
server.drone.start(pkg, next);
}, done);
} | [
"function",
"startDrones",
"(",
"pkg",
",",
"done",
")",
"{",
"if",
"(",
"pkg",
".",
"drones",
"==",
"0",
")",
"{",
"return",
"done",
"(",
")",
";",
"}",
"var",
"started",
"=",
"0",
";",
"async",
".",
"whilst",
"(",
"function",
"(",
")",
"{",
"return",
"started",
"<",
"pkg",
".",
"drones",
";",
"}",
",",
"function",
"(",
"next",
")",
"{",
"started",
"++",
";",
"server",
".",
"drone",
".",
"start",
"(",
"pkg",
",",
"next",
")",
";",
"}",
",",
"done",
")",
";",
"}"
] | Helper function which starts multiple drones a given application. | [
"Helper",
"function",
"which",
"starts",
"multiple",
"drones",
"a",
"given",
"application",
"."
] | 7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4 | https://github.com/nodejitsu/haibu/blob/7f59fbc852db2e2f3fed1bd7b3c4b2a461864cc4/lib/haibu/drone/index.js#L37-L50 |
21,876 | 3rd-Eden/diagnostics | adapters/asyncstorage.js | asyncstorage | async function asyncstorage(namespace) {
var debug, diagnostics;
try {
debug = await storage.getItem('debug');
diagnostics = await storage.getItem('diagnostics');
} catch (e) {
/* Nope, nothing. */
}
return enabled(namespace, debug || diagnostics || '');
} | javascript | async function asyncstorage(namespace) {
var debug, diagnostics;
try {
debug = await storage.getItem('debug');
diagnostics = await storage.getItem('diagnostics');
} catch (e) {
/* Nope, nothing. */
}
return enabled(namespace, debug || diagnostics || '');
} | [
"async",
"function",
"asyncstorage",
"(",
"namespace",
")",
"{",
"var",
"debug",
",",
"diagnostics",
";",
"try",
"{",
"debug",
"=",
"await",
"storage",
".",
"getItem",
"(",
"'debug'",
")",
";",
"diagnostics",
"=",
"await",
"storage",
".",
"getItem",
"(",
"'diagnostics'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"/* Nope, nothing. */",
"}",
"return",
"enabled",
"(",
"namespace",
",",
"debug",
"||",
"diagnostics",
"||",
"''",
")",
";",
"}"
] | AsyncStorage Adapter for React-Native
@param {String} namespace The namespace we should trigger on.
@return {Boolean} Indication if the namespace is allowed to log.
@public | [
"AsyncStorage",
"Adapter",
"for",
"React",
"-",
"Native"
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/adapters/asyncstorage.js#L16-L27 |
21,877 | 3rd-Eden/diagnostics | diagnostics.js | use | function use(adapter) {
if (~adapters.indexOf(adapter)) return false;
adapters.push(adapter);
return true;
} | javascript | function use(adapter) {
if (~adapters.indexOf(adapter)) return false;
adapters.push(adapter);
return true;
} | [
"function",
"use",
"(",
"adapter",
")",
"{",
"if",
"(",
"~",
"adapters",
".",
"indexOf",
"(",
"adapter",
")",
")",
"return",
"false",
";",
"adapters",
".",
"push",
"(",
"adapter",
")",
";",
"return",
"true",
";",
"}"
] | Register a new adapter that will used to find environments.
@param {Function} adapter A function that will return the possible env.
@returns {Boolean} Indication of a successful add.
@public | [
"Register",
"a",
"new",
"adapter",
"that",
"will",
"used",
"to",
"find",
"environments",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L31-L36 |
21,878 | 3rd-Eden/diagnostics | diagnostics.js | enabled | function enabled(namespace) {
var async = [];
for (var i = 0; i < adapters.length; i++) {
if (adapters[i].async) {
async.push(adapters[i]);
continue;
}
if (adapters[i](namespace)) return true;
}
if (!async.length) return false;
//
// Now that we know that we Async functions, we know we run in an ES6
// environment and can use all the API's that they offer, in this case
// we want to return a Promise so that we can `await` in React-Native
// for an async adapter.
//
return new Promise(function pinky(resolve) {
Promise.all(
async.map(function prebind(fn) {
return fn(namespace);
})
).then(function resolved(values) {
resolve(values.some(Boolean));
});
});
} | javascript | function enabled(namespace) {
var async = [];
for (var i = 0; i < adapters.length; i++) {
if (adapters[i].async) {
async.push(adapters[i]);
continue;
}
if (adapters[i](namespace)) return true;
}
if (!async.length) return false;
//
// Now that we know that we Async functions, we know we run in an ES6
// environment and can use all the API's that they offer, in this case
// we want to return a Promise so that we can `await` in React-Native
// for an async adapter.
//
return new Promise(function pinky(resolve) {
Promise.all(
async.map(function prebind(fn) {
return fn(namespace);
})
).then(function resolved(values) {
resolve(values.some(Boolean));
});
});
} | [
"function",
"enabled",
"(",
"namespace",
")",
"{",
"var",
"async",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"adapters",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"adapters",
"[",
"i",
"]",
".",
"async",
")",
"{",
"async",
".",
"push",
"(",
"adapters",
"[",
"i",
"]",
")",
";",
"continue",
";",
"}",
"if",
"(",
"adapters",
"[",
"i",
"]",
"(",
"namespace",
")",
")",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"async",
".",
"length",
")",
"return",
"false",
";",
"//",
"// Now that we know that we Async functions, we know we run in an ES6",
"// environment and can use all the API's that they offer, in this case",
"// we want to return a Promise so that we can `await` in React-Native",
"// for an async adapter.",
"//",
"return",
"new",
"Promise",
"(",
"function",
"pinky",
"(",
"resolve",
")",
"{",
"Promise",
".",
"all",
"(",
"async",
".",
"map",
"(",
"function",
"prebind",
"(",
"fn",
")",
"{",
"return",
"fn",
"(",
"namespace",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"resolved",
"(",
"values",
")",
"{",
"resolve",
"(",
"values",
".",
"some",
"(",
"Boolean",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Check if the namespace is allowed by any of our adapters.
@param {String} namespace The namespace that needs to be enabled
@returns {Boolean|Promise} Indication if the namespace is enabled by our adapters.
@public | [
"Check",
"if",
"the",
"namespace",
"is",
"allowed",
"by",
"any",
"of",
"our",
"adapters",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L55-L84 |
21,879 | 3rd-Eden/diagnostics | diagnostics.js | modify | function modify(fn) {
if (~modifiers.indexOf(fn)) return false;
modifiers.push(fn);
return true;
} | javascript | function modify(fn) {
if (~modifiers.indexOf(fn)) return false;
modifiers.push(fn);
return true;
} | [
"function",
"modify",
"(",
"fn",
")",
"{",
"if",
"(",
"~",
"modifiers",
".",
"indexOf",
"(",
"fn",
")",
")",
"return",
"false",
";",
"modifiers",
".",
"push",
"(",
"fn",
")",
";",
"return",
"true",
";",
"}"
] | Add a new message modifier to the debugger.
@param {Function} fn Modification function.
@returns {Boolean} Indication of a successful add.
@public | [
"Add",
"a",
"new",
"message",
"modifier",
"to",
"the",
"debugger",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L93-L98 |
21,880 | 3rd-Eden/diagnostics | diagnostics.js | process | function process(message) {
for (var i = 0; i < modifiers.length; i++) {
message = modifiers[i].apply(modifiers[i], arguments);
}
return message;
} | javascript | function process(message) {
for (var i = 0; i < modifiers.length; i++) {
message = modifiers[i].apply(modifiers[i], arguments);
}
return message;
} | [
"function",
"process",
"(",
"message",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"modifiers",
".",
"length",
";",
"i",
"++",
")",
"{",
"message",
"=",
"modifiers",
"[",
"i",
"]",
".",
"apply",
"(",
"modifiers",
"[",
"i",
"]",
",",
"arguments",
")",
";",
"}",
"return",
"message",
";",
"}"
] | Process the message with the modifiers.
@param {Mixed} message The message to be transformed by modifers.
@returns {String} Transformed message.
@public | [
"Process",
"the",
"message",
"with",
"the",
"modifiers",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L118-L124 |
21,881 | 3rd-Eden/diagnostics | diagnostics.js | introduce | function introduce(fn, options) {
var has = Object.prototype.hasOwnProperty;
for (var key in options) {
if (has.call(options, key)) {
fn[key] = options[key];
}
}
return fn;
} | javascript | function introduce(fn, options) {
var has = Object.prototype.hasOwnProperty;
for (var key in options) {
if (has.call(options, key)) {
fn[key] = options[key];
}
}
return fn;
} | [
"function",
"introduce",
"(",
"fn",
",",
"options",
")",
"{",
"var",
"has",
"=",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
";",
"for",
"(",
"var",
"key",
"in",
"options",
")",
"{",
"if",
"(",
"has",
".",
"call",
"(",
"options",
",",
"key",
")",
")",
"{",
"fn",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"fn",
";",
"}"
] | Introduce options to the logger function.
@param {Function} fn Calback function.
@param {Object} options Properties to introduce on fn.
@returns {Function} The passed function
@public | [
"Introduce",
"options",
"to",
"the",
"logger",
"function",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L134-L144 |
21,882 | 3rd-Eden/diagnostics | diagnostics.js | nope | function nope(options) {
options.enabled = false;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(function diagnopes() {
return false;
}, options);
} | javascript | function nope(options) {
options.enabled = false;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(function diagnopes() {
return false;
}, options);
} | [
"function",
"nope",
"(",
"options",
")",
"{",
"options",
".",
"enabled",
"=",
"false",
";",
"options",
".",
"modify",
"=",
"modify",
";",
"options",
".",
"set",
"=",
"set",
";",
"options",
".",
"use",
"=",
"use",
";",
"return",
"introduce",
"(",
"function",
"diagnopes",
"(",
")",
"{",
"return",
"false",
";",
"}",
",",
"options",
")",
";",
"}"
] | Nope, we're not allowed to write messages.
@returns {Boolean} false
@public | [
"Nope",
"we",
"re",
"not",
"allowed",
"to",
"write",
"messages",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L152-L161 |
21,883 | 3rd-Eden/diagnostics | diagnostics.js | yep | function yep(options) {
/**
* The function that receives the actual debug information.
*
* @returns {Boolean} indication that we're logging.
* @public
*/
function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
}
options.enabled = true;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(diagnostics, options);
} | javascript | function yep(options) {
/**
* The function that receives the actual debug information.
*
* @returns {Boolean} indication that we're logging.
* @public
*/
function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
}
options.enabled = true;
options.modify = modify;
options.set = set;
options.use = use;
return introduce(diagnostics, options);
} | [
"function",
"yep",
"(",
"options",
")",
"{",
"/**\n * The function that receives the actual debug information.\n *\n * @returns {Boolean} indication that we're logging.\n * @public\n */",
"function",
"diagnostics",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"write",
".",
"call",
"(",
"write",
",",
"options",
",",
"process",
"(",
"args",
",",
"options",
")",
")",
";",
"return",
"true",
";",
"}",
"options",
".",
"enabled",
"=",
"true",
";",
"options",
".",
"modify",
"=",
"modify",
";",
"options",
".",
"set",
"=",
"set",
";",
"options",
".",
"use",
"=",
"use",
";",
"return",
"introduce",
"(",
"diagnostics",
",",
"options",
")",
";",
"}"
] | Yep, we're allowed to write debug messages.
@param {Object} options The options for the process.
@returns {Function} The function that does the logging.
@public | [
"Yep",
"we",
"re",
"allowed",
"to",
"write",
"debug",
"messages",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L170-L190 |
21,884 | 3rd-Eden/diagnostics | diagnostics.js | diagnostics | function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
} | javascript | function diagnostics() {
var args = Array.prototype.slice.call(arguments, 0);
write.call(write, options, process(args, options));
return true;
} | [
"function",
"diagnostics",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"write",
".",
"call",
"(",
"write",
",",
"options",
",",
"process",
"(",
"args",
",",
"options",
")",
")",
";",
"return",
"true",
";",
"}"
] | The function that receives the actual debug information.
@returns {Boolean} indication that we're logging.
@public | [
"The",
"function",
"that",
"receives",
"the",
"actual",
"debug",
"information",
"."
] | a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1 | https://github.com/3rd-Eden/diagnostics/blob/a37d632b2e7049d3ea79fbe2eb7d1165cbba6fb1/diagnostics.js#L177-L182 |
21,885 | canjs/can-legacy-view-helpers | src/view.js | function(fn) {
return function() {
var realArgs = [];
var fnArgs = arguments;
each(fnArgs, function(val, i) {
if (i <= fnArgs.length) {
while (val && val.isComputed) {
val = val();
}
realArgs.push(val);
}
});
return fn.apply(this, realArgs);
};
} | javascript | function(fn) {
return function() {
var realArgs = [];
var fnArgs = arguments;
each(fnArgs, function(val, i) {
if (i <= fnArgs.length) {
while (val && val.isComputed) {
val = val();
}
realArgs.push(val);
}
});
return fn.apply(this, realArgs);
};
} | [
"function",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"realArgs",
"=",
"[",
"]",
";",
"var",
"fnArgs",
"=",
"arguments",
";",
"each",
"(",
"fnArgs",
",",
"function",
"(",
"val",
",",
"i",
")",
"{",
"if",
"(",
"i",
"<=",
"fnArgs",
".",
"length",
")",
"{",
"while",
"(",
"val",
"&&",
"val",
".",
"isComputed",
")",
"{",
"val",
"=",
"val",
"(",
")",
";",
"}",
"realArgs",
".",
"push",
"(",
"val",
")",
";",
"}",
"}",
")",
";",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"realArgs",
")",
";",
"}",
";",
"}"
] | Returns a function that automatically converts all computes passed to it | [
"Returns",
"a",
"function",
"that",
"automatically",
"converts",
"all",
"computes",
"passed",
"to",
"it"
] | 42886b363251b693d835d869816fcedb0c74b114 | https://github.com/canjs/can-legacy-view-helpers/blob/42886b363251b693d835d869816fcedb0c74b114/src/view.js#L751-L765 | |
21,886 | canjs/can-legacy-view-helpers | src/render.js | function () {
var old = view.lists,
data;
view.lists = function (list, renderer) {
data = {
list: list,
renderer: renderer
};
return Math.random();
};
// sets back to the old data
return function () {
view.lists = old;
return data;
};
} | javascript | function () {
var old = view.lists,
data;
view.lists = function (list, renderer) {
data = {
list: list,
renderer: renderer
};
return Math.random();
};
// sets back to the old data
return function () {
view.lists = old;
return data;
};
} | [
"function",
"(",
")",
"{",
"var",
"old",
"=",
"view",
".",
"lists",
",",
"data",
";",
"view",
".",
"lists",
"=",
"function",
"(",
"list",
",",
"renderer",
")",
"{",
"data",
"=",
"{",
"list",
":",
"list",
",",
"renderer",
":",
"renderer",
"}",
";",
"return",
"Math",
".",
"random",
"(",
")",
";",
"}",
";",
"// sets back to the old data",
"return",
"function",
"(",
")",
"{",
"view",
".",
"lists",
"=",
"old",
";",
"return",
"data",
";",
"}",
";",
"}"
] | called in text to make a temporary can.view.lists function that can be called with the list to iterate over and the template used to produce the content within the list | [
"called",
"in",
"text",
"to",
"make",
"a",
"temporary",
"can",
".",
"view",
".",
"lists",
"function",
"that",
"can",
"be",
"called",
"with",
"the",
"list",
"to",
"iterate",
"over",
"and",
"the",
"template",
"used",
"to",
"produce",
"the",
"content",
"within",
"the",
"list"
] | 42886b363251b693d835d869816fcedb0c74b114 | https://github.com/canjs/can-legacy-view-helpers/blob/42886b363251b693d835d869816fcedb0c74b114/src/render.js#L77-L94 | |
21,887 | medea/medea | hint_file_parser.js | function(dirname, keydir, dataFile, cb1) {
var fileId = Number(path.basename(dataFile, '.medea.data'));
var file = new DataFileParser({ filename: dataFile });
file.on('error', cb1);
file.on('entry', function(entry) {
var key = entry.key.toString();
if (key.length === 0) {
return;
}
if (!keydir.has(key) || (keydir.has(key) && keydir.get(key).fileId === fileId)) {
var kEntry = new KeyDirEntry();
kEntry.key = key;
kEntry.fileId = fileId;
kEntry.timestamp = entry.timestamp;
kEntry.valueSize = entry.valueSize;
kEntry.valuePosition = entry.valuePosition;
keydir.set(key, kEntry);
}
});
file.on('end', cb1);
file.parse();
} | javascript | function(dirname, keydir, dataFile, cb1) {
var fileId = Number(path.basename(dataFile, '.medea.data'));
var file = new DataFileParser({ filename: dataFile });
file.on('error', cb1);
file.on('entry', function(entry) {
var key = entry.key.toString();
if (key.length === 0) {
return;
}
if (!keydir.has(key) || (keydir.has(key) && keydir.get(key).fileId === fileId)) {
var kEntry = new KeyDirEntry();
kEntry.key = key;
kEntry.fileId = fileId;
kEntry.timestamp = entry.timestamp;
kEntry.valueSize = entry.valueSize;
kEntry.valuePosition = entry.valuePosition;
keydir.set(key, kEntry);
}
});
file.on('end', cb1);
file.parse();
} | [
"function",
"(",
"dirname",
",",
"keydir",
",",
"dataFile",
",",
"cb1",
")",
"{",
"var",
"fileId",
"=",
"Number",
"(",
"path",
".",
"basename",
"(",
"dataFile",
",",
"'.medea.data'",
")",
")",
";",
"var",
"file",
"=",
"new",
"DataFileParser",
"(",
"{",
"filename",
":",
"dataFile",
"}",
")",
";",
"file",
".",
"on",
"(",
"'error'",
",",
"cb1",
")",
";",
"file",
".",
"on",
"(",
"'entry'",
",",
"function",
"(",
"entry",
")",
"{",
"var",
"key",
"=",
"entry",
".",
"key",
".",
"toString",
"(",
")",
";",
"if",
"(",
"key",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"keydir",
".",
"has",
"(",
"key",
")",
"||",
"(",
"keydir",
".",
"has",
"(",
"key",
")",
"&&",
"keydir",
".",
"get",
"(",
"key",
")",
".",
"fileId",
"===",
"fileId",
")",
")",
"{",
"var",
"kEntry",
"=",
"new",
"KeyDirEntry",
"(",
")",
";",
"kEntry",
".",
"key",
"=",
"key",
";",
"kEntry",
".",
"fileId",
"=",
"fileId",
";",
"kEntry",
".",
"timestamp",
"=",
"entry",
".",
"timestamp",
";",
"kEntry",
".",
"valueSize",
"=",
"entry",
".",
"valueSize",
";",
"kEntry",
".",
"valuePosition",
"=",
"entry",
".",
"valuePosition",
";",
"keydir",
".",
"set",
"(",
"key",
",",
"kEntry",
")",
";",
"}",
"}",
")",
";",
"file",
".",
"on",
"(",
"'end'",
",",
"cb1",
")",
";",
"file",
".",
"parse",
"(",
")",
";",
"}"
] | parse data file for keys when hint file is missing | [
"parse",
"data",
"file",
"for",
"keys",
"when",
"hint",
"file",
"is",
"missing"
] | 3438fbcf7ce3c89b9ec52b4523a164db43e261a2 | https://github.com/medea/medea/blob/3438fbcf7ce3c89b9ec52b4523a164db43e261a2/hint_file_parser.js#L20-L43 | |
21,888 | AlexGalays/kaiju | src/lib/message.js | PartiallyAppliedMessage | function PartiallyAppliedMessage(underlyingMessage, payload) {
function message(...otherPayloads) {
return underlyingMessage.apply(null, [payload, ...otherPayloads])
}
message.type = 'partiallyAppliedMessage'
message._id = underlyingMessage._id
message._name = underlyingMessage._name
message._isMessage = true
message.with = withPayload
// Used for VDOM Diffing (See util/shallowEqual)
message.payload = payload
return message
} | javascript | function PartiallyAppliedMessage(underlyingMessage, payload) {
function message(...otherPayloads) {
return underlyingMessage.apply(null, [payload, ...otherPayloads])
}
message.type = 'partiallyAppliedMessage'
message._id = underlyingMessage._id
message._name = underlyingMessage._name
message._isMessage = true
message.with = withPayload
// Used for VDOM Diffing (See util/shallowEqual)
message.payload = payload
return message
} | [
"function",
"PartiallyAppliedMessage",
"(",
"underlyingMessage",
",",
"payload",
")",
"{",
"function",
"message",
"(",
"...",
"otherPayloads",
")",
"{",
"return",
"underlyingMessage",
".",
"apply",
"(",
"null",
",",
"[",
"payload",
",",
"...",
"otherPayloads",
"]",
")",
"}",
"message",
".",
"type",
"=",
"'partiallyAppliedMessage'",
"message",
".",
"_id",
"=",
"underlyingMessage",
".",
"_id",
"message",
".",
"_name",
"=",
"underlyingMessage",
".",
"_name",
"message",
".",
"_isMessage",
"=",
"true",
"message",
".",
"with",
"=",
"withPayload",
"// Used for VDOM Diffing (See util/shallowEqual)",
"message",
".",
"payload",
"=",
"payload",
"return",
"message",
"}"
] | Creates a new Message type that is partially applied with a payload | [
"Creates",
"a",
"new",
"Message",
"type",
"that",
"is",
"partially",
"applied",
"with",
"a",
"payload"
] | 54d6118f4ebdf0725a907c87be7f262405e16e48 | https://github.com/AlexGalays/kaiju/blob/54d6118f4ebdf0725a907c87be7f262405e16e48/src/lib/message.js#L35-L53 |
21,889 | AlexGalays/kaiju | src/lib/component.js | postpatch | function postpatch(oldVnode, vnode) {
const oldData = oldVnode.data
const newData = vnode.data
// Server side rendering: Reconcilating with a server-rendered node will have skipped calling insert()
if (!oldData.component) {
insert(vnode)
}
// oldData wouldn't have a component reference set if it came from the server (it's first set in insert())
const component = oldData.component || newData.component
const oldProps = component.props
const newProps = newData.component.props
// Update the original component with any property that may have changed during this render pass
component.props = newProps
newData.component = component
// If the props changed, render immediately as we are already
// in the render context of our parent
if (!shallowEqual(oldProps, newProps)) {
component.lifecycle.propsChanging = true
component.lifecycle.propsChanged(newProps)
component.lifecycle.propsChanging = false
renderComponentNow(component)
}
} | javascript | function postpatch(oldVnode, vnode) {
const oldData = oldVnode.data
const newData = vnode.data
// Server side rendering: Reconcilating with a server-rendered node will have skipped calling insert()
if (!oldData.component) {
insert(vnode)
}
// oldData wouldn't have a component reference set if it came from the server (it's first set in insert())
const component = oldData.component || newData.component
const oldProps = component.props
const newProps = newData.component.props
// Update the original component with any property that may have changed during this render pass
component.props = newProps
newData.component = component
// If the props changed, render immediately as we are already
// in the render context of our parent
if (!shallowEqual(oldProps, newProps)) {
component.lifecycle.propsChanging = true
component.lifecycle.propsChanged(newProps)
component.lifecycle.propsChanging = false
renderComponentNow(component)
}
} | [
"function",
"postpatch",
"(",
"oldVnode",
",",
"vnode",
")",
"{",
"const",
"oldData",
"=",
"oldVnode",
".",
"data",
"const",
"newData",
"=",
"vnode",
".",
"data",
"// Server side rendering: Reconcilating with a server-rendered node will have skipped calling insert()",
"if",
"(",
"!",
"oldData",
".",
"component",
")",
"{",
"insert",
"(",
"vnode",
")",
"}",
"// oldData wouldn't have a component reference set if it came from the server (it's first set in insert())",
"const",
"component",
"=",
"oldData",
".",
"component",
"||",
"newData",
".",
"component",
"const",
"oldProps",
"=",
"component",
".",
"props",
"const",
"newProps",
"=",
"newData",
".",
"component",
".",
"props",
"// Update the original component with any property that may have changed during this render pass",
"component",
".",
"props",
"=",
"newProps",
"newData",
".",
"component",
"=",
"component",
"// If the props changed, render immediately as we are already",
"// in the render context of our parent",
"if",
"(",
"!",
"shallowEqual",
"(",
"oldProps",
",",
"newProps",
")",
")",
"{",
"component",
".",
"lifecycle",
".",
"propsChanging",
"=",
"true",
"component",
".",
"lifecycle",
".",
"propsChanged",
"(",
"newProps",
")",
"component",
".",
"lifecycle",
".",
"propsChanging",
"=",
"false",
"renderComponentNow",
"(",
"component",
")",
"}",
"}"
] | Called on every parent re-render, this is where the props passed by the component's parent may have changed. | [
"Called",
"on",
"every",
"parent",
"re",
"-",
"render",
"this",
"is",
"where",
"the",
"props",
"passed",
"by",
"the",
"component",
"s",
"parent",
"may",
"have",
"changed",
"."
] | 54d6118f4ebdf0725a907c87be7f262405e16e48 | https://github.com/AlexGalays/kaiju/blob/54d6118f4ebdf0725a907c87be7f262405e16e48/src/lib/component.js#L105-L134 |
21,890 | jonschlinkert/github-base | lib/utils.js | createHeaders | function createHeaders(options) {
const opts = Object.assign({}, options);
const headers = Object.assign({}, defaultHeaders, lowercaseKeys(opts.headers || {}));
if (!opts.bearer && !opts.token && !opts.username && !opts.password) {
return headers;
}
if (opts.token) {
headers['authorization'] = 'token ' + opts.token;
return headers;
}
if (opts.bearer) {
headers['authorization'] = 'Bearer ' + opts.bearer;
return headers;
}
const creds = opts.username + ':' + opts.password;
headers['authorization'] = 'Basic ' + toBase64(creds);
return headers;
} | javascript | function createHeaders(options) {
const opts = Object.assign({}, options);
const headers = Object.assign({}, defaultHeaders, lowercaseKeys(opts.headers || {}));
if (!opts.bearer && !opts.token && !opts.username && !opts.password) {
return headers;
}
if (opts.token) {
headers['authorization'] = 'token ' + opts.token;
return headers;
}
if (opts.bearer) {
headers['authorization'] = 'Bearer ' + opts.bearer;
return headers;
}
const creds = opts.username + ':' + opts.password;
headers['authorization'] = 'Basic ' + toBase64(creds);
return headers;
} | [
"function",
"createHeaders",
"(",
"options",
")",
"{",
"const",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"const",
"headers",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultHeaders",
",",
"lowercaseKeys",
"(",
"opts",
".",
"headers",
"||",
"{",
"}",
")",
")",
";",
"if",
"(",
"!",
"opts",
".",
"bearer",
"&&",
"!",
"opts",
".",
"token",
"&&",
"!",
"opts",
".",
"username",
"&&",
"!",
"opts",
".",
"password",
")",
"{",
"return",
"headers",
";",
"}",
"if",
"(",
"opts",
".",
"token",
")",
"{",
"headers",
"[",
"'authorization'",
"]",
"=",
"'token '",
"+",
"opts",
".",
"token",
";",
"return",
"headers",
";",
"}",
"if",
"(",
"opts",
".",
"bearer",
")",
"{",
"headers",
"[",
"'authorization'",
"]",
"=",
"'Bearer '",
"+",
"opts",
".",
"bearer",
";",
"return",
"headers",
";",
"}",
"const",
"creds",
"=",
"opts",
".",
"username",
"+",
"':'",
"+",
"opts",
".",
"password",
";",
"headers",
"[",
"'authorization'",
"]",
"=",
"'Basic '",
"+",
"toBase64",
"(",
"creds",
")",
";",
"return",
"headers",
";",
"}"
] | Create auth string - token, Bearer or Basic Auth | [
"Create",
"auth",
"string",
"-",
"token",
"Bearer",
"or",
"Basic",
"Auth"
] | 2fd664e3f9a3ad24758401bf98743d553875d2cf | https://github.com/jonschlinkert/github-base/blob/2fd664e3f9a3ad24758401bf98743d553875d2cf/lib/utils.js#L113-L134 |
21,891 | jonschlinkert/github-base | lib/utils.js | interpolate | function interpolate(str, context) {
const opts = { ...context.options };
let val = opts.apiurl + str.replace(/:([\w_]+)/g, (m, key) => {
opts.params = union(opts.params, key);
let val = get(opts, key);
if (val !== void 0) {
return val;
}
return key;
});
if (opts.method.toLowerCase() === 'get' && opts.paged !== false) {
const obj = url.parse(val);
const query = obj.query ? qs.parse(obj.query) : {};
const noquery = omit(obj, ['query', 'search']);
noquery.query = noquery.search = qs.stringify(Object.assign({ per_page: 100 }, opts.query, query));
val = url.format(noquery);
}
val += /\?/.test(val) ? '&' : '?';
val += (new Date()).getTime();
return val;
} | javascript | function interpolate(str, context) {
const opts = { ...context.options };
let val = opts.apiurl + str.replace(/:([\w_]+)/g, (m, key) => {
opts.params = union(opts.params, key);
let val = get(opts, key);
if (val !== void 0) {
return val;
}
return key;
});
if (opts.method.toLowerCase() === 'get' && opts.paged !== false) {
const obj = url.parse(val);
const query = obj.query ? qs.parse(obj.query) : {};
const noquery = omit(obj, ['query', 'search']);
noquery.query = noquery.search = qs.stringify(Object.assign({ per_page: 100 }, opts.query, query));
val = url.format(noquery);
}
val += /\?/.test(val) ? '&' : '?';
val += (new Date()).getTime();
return val;
} | [
"function",
"interpolate",
"(",
"str",
",",
"context",
")",
"{",
"const",
"opts",
"=",
"{",
"...",
"context",
".",
"options",
"}",
";",
"let",
"val",
"=",
"opts",
".",
"apiurl",
"+",
"str",
".",
"replace",
"(",
"/",
":([\\w_]+)",
"/",
"g",
",",
"(",
"m",
",",
"key",
")",
"=>",
"{",
"opts",
".",
"params",
"=",
"union",
"(",
"opts",
".",
"params",
",",
"key",
")",
";",
"let",
"val",
"=",
"get",
"(",
"opts",
",",
"key",
")",
";",
"if",
"(",
"val",
"!==",
"void",
"0",
")",
"{",
"return",
"val",
";",
"}",
"return",
"key",
";",
"}",
")",
";",
"if",
"(",
"opts",
".",
"method",
".",
"toLowerCase",
"(",
")",
"===",
"'get'",
"&&",
"opts",
".",
"paged",
"!==",
"false",
")",
"{",
"const",
"obj",
"=",
"url",
".",
"parse",
"(",
"val",
")",
";",
"const",
"query",
"=",
"obj",
".",
"query",
"?",
"qs",
".",
"parse",
"(",
"obj",
".",
"query",
")",
":",
"{",
"}",
";",
"const",
"noquery",
"=",
"omit",
"(",
"obj",
",",
"[",
"'query'",
",",
"'search'",
"]",
")",
";",
"noquery",
".",
"query",
"=",
"noquery",
".",
"search",
"=",
"qs",
".",
"stringify",
"(",
"Object",
".",
"assign",
"(",
"{",
"per_page",
":",
"100",
"}",
",",
"opts",
".",
"query",
",",
"query",
")",
")",
";",
"val",
"=",
"url",
".",
"format",
"(",
"noquery",
")",
";",
"}",
"val",
"+=",
"/",
"\\?",
"/",
".",
"test",
"(",
"val",
")",
"?",
"'&'",
":",
"'?'",
";",
"val",
"+=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
";",
"return",
"val",
";",
"}"
] | Create request URL by replacing params with actual values. | [
"Create",
"request",
"URL",
"by",
"replacing",
"params",
"with",
"actual",
"values",
"."
] | 2fd664e3f9a3ad24758401bf98743d553875d2cf | https://github.com/jonschlinkert/github-base/blob/2fd664e3f9a3ad24758401bf98743d553875d2cf/lib/utils.js#L140-L163 |
21,892 | jonschlinkert/github-base | lib/utils.js | sanitize | function sanitize(options, blacklist) {
const opts = Object.assign({}, options);
const defaults = ['apiurl', 'token', 'username', 'password', 'placeholders', 'bearer'];
const keys = union([], defaults, blacklist);
return omit(opts, keys);
} | javascript | function sanitize(options, blacklist) {
const opts = Object.assign({}, options);
const defaults = ['apiurl', 'token', 'username', 'password', 'placeholders', 'bearer'];
const keys = union([], defaults, blacklist);
return omit(opts, keys);
} | [
"function",
"sanitize",
"(",
"options",
",",
"blacklist",
")",
"{",
"const",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"const",
"defaults",
"=",
"[",
"'apiurl'",
",",
"'token'",
",",
"'username'",
",",
"'password'",
",",
"'placeholders'",
",",
"'bearer'",
"]",
";",
"const",
"keys",
"=",
"union",
"(",
"[",
"]",
",",
"defaults",
",",
"blacklist",
")",
";",
"return",
"omit",
"(",
"opts",
",",
"keys",
")",
";",
"}"
] | Cleanup request options object | [
"Cleanup",
"request",
"options",
"object"
] | 2fd664e3f9a3ad24758401bf98743d553875d2cf | https://github.com/jonschlinkert/github-base/blob/2fd664e3f9a3ad24758401bf98743d553875d2cf/lib/utils.js#L189-L194 |
21,893 | syntax-tree/unist-util-is | index.js | is | function is(test, node, index, parent, context) {
var hasParent = parent !== null && parent !== undefined
var hasIndex = index !== null && index !== undefined
var check = convert(test)
if (
hasIndex &&
(typeof index !== 'number' || index < 0 || index === Infinity)
) {
throw new Error('Expected positive finite index or child node')
}
if (hasParent && (!is(null, parent) || !parent.children)) {
throw new Error('Expected parent node')
}
if (!node || !node.type || typeof node.type !== 'string') {
return false
}
if (hasParent !== hasIndex) {
throw new Error('Expected both parent and index')
}
return Boolean(check.call(context, node, index, parent))
} | javascript | function is(test, node, index, parent, context) {
var hasParent = parent !== null && parent !== undefined
var hasIndex = index !== null && index !== undefined
var check = convert(test)
if (
hasIndex &&
(typeof index !== 'number' || index < 0 || index === Infinity)
) {
throw new Error('Expected positive finite index or child node')
}
if (hasParent && (!is(null, parent) || !parent.children)) {
throw new Error('Expected parent node')
}
if (!node || !node.type || typeof node.type !== 'string') {
return false
}
if (hasParent !== hasIndex) {
throw new Error('Expected both parent and index')
}
return Boolean(check.call(context, node, index, parent))
} | [
"function",
"is",
"(",
"test",
",",
"node",
",",
"index",
",",
"parent",
",",
"context",
")",
"{",
"var",
"hasParent",
"=",
"parent",
"!==",
"null",
"&&",
"parent",
"!==",
"undefined",
"var",
"hasIndex",
"=",
"index",
"!==",
"null",
"&&",
"index",
"!==",
"undefined",
"var",
"check",
"=",
"convert",
"(",
"test",
")",
"if",
"(",
"hasIndex",
"&&",
"(",
"typeof",
"index",
"!==",
"'number'",
"||",
"index",
"<",
"0",
"||",
"index",
"===",
"Infinity",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected positive finite index or child node'",
")",
"}",
"if",
"(",
"hasParent",
"&&",
"(",
"!",
"is",
"(",
"null",
",",
"parent",
")",
"||",
"!",
"parent",
".",
"children",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected parent node'",
")",
"}",
"if",
"(",
"!",
"node",
"||",
"!",
"node",
".",
"type",
"||",
"typeof",
"node",
".",
"type",
"!==",
"'string'",
")",
"{",
"return",
"false",
"}",
"if",
"(",
"hasParent",
"!==",
"hasIndex",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expected both parent and index'",
")",
"}",
"return",
"Boolean",
"(",
"check",
".",
"call",
"(",
"context",
",",
"node",
",",
"index",
",",
"parent",
")",
")",
"}"
] | Assert if `test` passes for `node`. When a `parent` node is known the `index` of node. | [
"Assert",
"if",
"test",
"passes",
"for",
"node",
".",
"When",
"a",
"parent",
"node",
"is",
"known",
"the",
"index",
"of",
"node",
"."
] | 35b280ee14ad215280fe6da89a33275c813265ae | https://github.com/syntax-tree/unist-util-is/blob/35b280ee14ad215280fe6da89a33275c813265ae/index.js#L9-L34 |
21,894 | syntax-tree/unist-util-is | index.js | matchesFactory | function matchesFactory(test) {
return matches
function matches(node) {
var key
for (key in test) {
if (node[key] !== test[key]) {
return false
}
}
return true
}
} | javascript | function matchesFactory(test) {
return matches
function matches(node) {
var key
for (key in test) {
if (node[key] !== test[key]) {
return false
}
}
return true
}
} | [
"function",
"matchesFactory",
"(",
"test",
")",
"{",
"return",
"matches",
"function",
"matches",
"(",
"node",
")",
"{",
"var",
"key",
"for",
"(",
"key",
"in",
"test",
")",
"{",
"if",
"(",
"node",
"[",
"key",
"]",
"!==",
"test",
"[",
"key",
"]",
")",
"{",
"return",
"false",
"}",
"}",
"return",
"true",
"}",
"}"
] | Utility assert each property in `test` is represented in `node`, and each values are strictly equal. | [
"Utility",
"assert",
"each",
"property",
"in",
"test",
"is",
"represented",
"in",
"node",
"and",
"each",
"values",
"are",
"strictly",
"equal",
"."
] | 35b280ee14ad215280fe6da89a33275c813265ae | https://github.com/syntax-tree/unist-util-is/blob/35b280ee14ad215280fe6da89a33275c813265ae/index.js#L70-L84 |
21,895 | virtyaluk/paper-ripple | dist/paperRipple.jquery.js | ElementRect | function ElementRect(element) {
_classCallCheck(this, ElementRect);
this._element = element;
/**
* Returns the width of the current element.
*
* @type {Number}
*/
this.width = this.boundingRect.width;
/**
* Returns the height of the current element.
*
* @type {Number}
*/
this.height = this.boundingRect.height;
/**
* Returns the size (the biggest side) of the current element.
*
* @type {number}
*/
this.size = Math.max(this.width, this.height);
return this;
} | javascript | function ElementRect(element) {
_classCallCheck(this, ElementRect);
this._element = element;
/**
* Returns the width of the current element.
*
* @type {Number}
*/
this.width = this.boundingRect.width;
/**
* Returns the height of the current element.
*
* @type {Number}
*/
this.height = this.boundingRect.height;
/**
* Returns the size (the biggest side) of the current element.
*
* @type {number}
*/
this.size = Math.max(this.width, this.height);
return this;
} | [
"function",
"ElementRect",
"(",
"element",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"ElementRect",
")",
";",
"this",
".",
"_element",
"=",
"element",
";",
"/**\n * Returns the width of the current element.\n *\n * @type {Number}\n */",
"this",
".",
"width",
"=",
"this",
".",
"boundingRect",
".",
"width",
";",
"/**\n * Returns the height of the current element.\n *\n * @type {Number}\n */",
"this",
".",
"height",
"=",
"this",
".",
"boundingRect",
".",
"height",
";",
"/**\n * Returns the size (the biggest side) of the current element.\n *\n * @type {number}\n */",
"this",
".",
"size",
"=",
"Math",
".",
"max",
"(",
"this",
".",
"width",
",",
"this",
".",
"height",
")",
";",
"return",
"this",
";",
"}"
] | Initializes a new instance of the `ElementRect` class with the specified `element`.
@constructs ElementRect
@param {HTMLElement} element - The DOM element to get metrics from
@returns {ElementRect} The new instance of a class. | [
"Initializes",
"a",
"new",
"instance",
"of",
"the",
"ElementRect",
"class",
"with",
"the",
"specified",
"element",
"."
] | 4e8507eb1ff3d69328e54ce7ea3fa7f7ad6d67da | https://github.com/virtyaluk/paper-ripple/blob/4e8507eb1ff3d69328e54ce7ea3fa7f7ad6d67da/dist/paperRipple.jquery.js#L46-L73 |
21,896 | cmrd-senya/markdown-it-html5-embed | lib/index.js | translate | function translate(messageObj) {
// Default to English if we don't have this message, or don't support this
// language at all
var language = messageObj.language && this[messageObj.language] &&
this[messageObj.language][messageObj.messageKey] ?
messageObj.language :
'en';
var rv = this[language][messageObj.messageKey];
if (messageObj.messageParam) {
rv = rv.replace('%s', messageObj.messageParam);
}
return rv;
} | javascript | function translate(messageObj) {
// Default to English if we don't have this message, or don't support this
// language at all
var language = messageObj.language && this[messageObj.language] &&
this[messageObj.language][messageObj.messageKey] ?
messageObj.language :
'en';
var rv = this[language][messageObj.messageKey];
if (messageObj.messageParam) {
rv = rv.replace('%s', messageObj.messageParam);
}
return rv;
} | [
"function",
"translate",
"(",
"messageObj",
")",
"{",
"// Default to English if we don't have this message, or don't support this",
"// language at all",
"var",
"language",
"=",
"messageObj",
".",
"language",
"&&",
"this",
"[",
"messageObj",
".",
"language",
"]",
"&&",
"this",
"[",
"messageObj",
".",
"language",
"]",
"[",
"messageObj",
".",
"messageKey",
"]",
"?",
"messageObj",
".",
"language",
":",
"'en'",
";",
"var",
"rv",
"=",
"this",
"[",
"language",
"]",
"[",
"messageObj",
".",
"messageKey",
"]",
";",
"if",
"(",
"messageObj",
".",
"messageParam",
")",
"{",
"rv",
"=",
"rv",
".",
"replace",
"(",
"'%s'",
",",
"messageObj",
".",
"messageParam",
")",
";",
"}",
"return",
"rv",
";",
"}"
] | Very basic translation function. To translate or customize the UI messages,
set options.messages. To also customize the translation function itself, set
option.translateFn to a function that handles the same message object format.
@param {Object} messageObj
the message object
@param {String} messageObj.messageKey
an identifier used for looking up the message in i18n files
@param {String} messageObj.messageParam
for substitution of %s for filename and description in the respective
messages
@param {String} [messageObj.language='en']
a language code, ignored in the default implementation
@this {Object}
the built-in default messages, or options.messages if set | [
"Very",
"basic",
"translation",
"function",
".",
"To",
"translate",
"or",
"customize",
"the",
"UI",
"messages",
"set",
"options",
".",
"messages",
".",
"To",
"also",
"customize",
"the",
"translation",
"function",
"itself",
"set",
"option",
".",
"translateFn",
"to",
"a",
"function",
"that",
"handles",
"the",
"same",
"message",
"object",
"format",
"."
] | 9f9b729bdf7629b415fa46aface73c905db37aad | https://github.com/cmrd-senya/markdown-it-html5-embed/blob/9f9b729bdf7629b415fa46aface73c905db37aad/lib/index.js#L191-L204 |
21,897 | jonschlinkert/parse-csv | lib/renderer.js | Renderer | function Renderer(options) {
var defaults = {
headers: {
included: true,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma',
outputDataType: 'json',
columnDelimiter: "\t",
rowDelimiter: '\n',
inputHeader: {},
outputHeader: {},
dataSelect: {},
outputText: '',
newline: '\n',
indent: ' ',
commentLine: '//',
commentLineEnd: '',
tableName: 'converter',
useUnderscores: true,
includeWhiteSpace: true,
useTabsForIndent: false
};
this.options = merge({}, defaults, options);
if (this.options.includeWhiteSpace) {
this.options.newline = '\n';
} else {
this.options.indent = '';
this.options.newline = '';
}
} | javascript | function Renderer(options) {
var defaults = {
headers: {
included: true,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma',
outputDataType: 'json',
columnDelimiter: "\t",
rowDelimiter: '\n',
inputHeader: {},
outputHeader: {},
dataSelect: {},
outputText: '',
newline: '\n',
indent: ' ',
commentLine: '//',
commentLineEnd: '',
tableName: 'converter',
useUnderscores: true,
includeWhiteSpace: true,
useTabsForIndent: false
};
this.options = merge({}, defaults, options);
if (this.options.includeWhiteSpace) {
this.options.newline = '\n';
} else {
this.options.indent = '';
this.options.newline = '';
}
} | [
"function",
"Renderer",
"(",
"options",
")",
"{",
"var",
"defaults",
"=",
"{",
"headers",
":",
"{",
"included",
":",
"true",
",",
"downcase",
":",
"true",
",",
"upcase",
":",
"true",
"}",
",",
"delimiter",
":",
"'tab'",
",",
"decimalSign",
":",
"'comma'",
",",
"outputDataType",
":",
"'json'",
",",
"columnDelimiter",
":",
"\"\\t\"",
",",
"rowDelimiter",
":",
"'\\n'",
",",
"inputHeader",
":",
"{",
"}",
",",
"outputHeader",
":",
"{",
"}",
",",
"dataSelect",
":",
"{",
"}",
",",
"outputText",
":",
"''",
",",
"newline",
":",
"'\\n'",
",",
"indent",
":",
"' '",
",",
"commentLine",
":",
"'//'",
",",
"commentLineEnd",
":",
"''",
",",
"tableName",
":",
"'converter'",
",",
"useUnderscores",
":",
"true",
",",
"includeWhiteSpace",
":",
"true",
",",
"useTabsForIndent",
":",
"false",
"}",
";",
"this",
".",
"options",
"=",
"merge",
"(",
"{",
"}",
",",
"defaults",
",",
"options",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"includeWhiteSpace",
")",
"{",
"this",
".",
"options",
".",
"newline",
"=",
"'\\n'",
";",
"}",
"else",
"{",
"this",
".",
"options",
".",
"indent",
"=",
"''",
";",
"this",
".",
"options",
".",
"newline",
"=",
"''",
";",
"}",
"}"
] | Create a new `Renderer` with the given `options`.
```js
var csv = require('parse-csv');
var renderer = new csv.Renderer();
```
@param {Object} `options`
@api public | [
"Create",
"a",
"new",
"Renderer",
"with",
"the",
"given",
"options",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/renderer.js#L22-L61 |
21,898 | jonschlinkert/parse-csv | lib/parser.js | Parser | function Parser(options) {
this.options = merge({}, {
headers: {
included: false,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma'
}, options);
} | javascript | function Parser(options) {
this.options = merge({}, {
headers: {
included: false,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma'
}, options);
} | [
"function",
"Parser",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"merge",
"(",
"{",
"}",
",",
"{",
"headers",
":",
"{",
"included",
":",
"false",
",",
"downcase",
":",
"true",
",",
"upcase",
":",
"true",
"}",
",",
"delimiter",
":",
"'tab'",
",",
"decimalSign",
":",
"'comma'",
"}",
",",
"options",
")",
";",
"}"
] | Create a new `Parser` with the given `options`.
```js
var csv = require('parse-csv');
var parser = new csv.Parser();
```
@param {Options} `options`
@api public | [
"Create",
"a",
"new",
"Parser",
"with",
"the",
"given",
"options",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/parser.js#L30-L40 |
21,899 | jonschlinkert/parse-csv | lib/parser.js | toArray | function toArray(str, options) {
var opts = extend({delim: ','}, options);
// Create a regular expression to parse the CSV values.
var re = new RegExp(
// Delimiters.
'(\\' + opts.delim + '|\\n|^)' +
// Quoted fields.
'(?:"([^"]*(?:""[^"]*)*)"|' +
// Standard fields.
'([^"\\' + opts.delim + '\\n]*))', 'gi');
// Create an array to hold our data. Give the array
// a default empty first row.
var arr = [[]];
// Create an array to hold our individual pattern
// matching groups.
var match = null;
var value;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (match = re.exec(str)) {
// Get the delimiter that was found.
var matchedDelim = match[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If it does not, then we can expect
// this delimiter to be a row delimiter.
if (matchedDelim.length && (matchedDelim != opts.delim)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arr.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (match[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
value = match[2].replace(/""/g, '"');
} else {
// We found a non-quoted value.
value = match[3];
}
// Now that we have our value string, let's add
// it to the data array.
arr[arr.length - 1].push(value);
}
// Return the parsed data.
return arr;
} | javascript | function toArray(str, options) {
var opts = extend({delim: ','}, options);
// Create a regular expression to parse the CSV values.
var re = new RegExp(
// Delimiters.
'(\\' + opts.delim + '|\\n|^)' +
// Quoted fields.
'(?:"([^"]*(?:""[^"]*)*)"|' +
// Standard fields.
'([^"\\' + opts.delim + '\\n]*))', 'gi');
// Create an array to hold our data. Give the array
// a default empty first row.
var arr = [[]];
// Create an array to hold our individual pattern
// matching groups.
var match = null;
var value;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (match = re.exec(str)) {
// Get the delimiter that was found.
var matchedDelim = match[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If it does not, then we can expect
// this delimiter to be a row delimiter.
if (matchedDelim.length && (matchedDelim != opts.delim)) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arr.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (match[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
value = match[2].replace(/""/g, '"');
} else {
// We found a non-quoted value.
value = match[3];
}
// Now that we have our value string, let's add
// it to the data array.
arr[arr.length - 1].push(value);
}
// Return the parsed data.
return arr;
} | [
"function",
"toArray",
"(",
"str",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"extend",
"(",
"{",
"delim",
":",
"','",
"}",
",",
"options",
")",
";",
"// Create a regular expression to parse the CSV values.",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"// Delimiters.",
"'(\\\\'",
"+",
"opts",
".",
"delim",
"+",
"'|\\\\n|^)'",
"+",
"// Quoted fields.",
"'(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|'",
"+",
"// Standard fields.",
"'([^\"\\\\'",
"+",
"opts",
".",
"delim",
"+",
"'\\\\n]*))'",
",",
"'gi'",
")",
";",
"// Create an array to hold our data. Give the array",
"// a default empty first row.",
"var",
"arr",
"=",
"[",
"[",
"]",
"]",
";",
"// Create an array to hold our individual pattern",
"// matching groups.",
"var",
"match",
"=",
"null",
";",
"var",
"value",
";",
"// Keep looping over the regular expression matches",
"// until we can no longer find a match.",
"while",
"(",
"match",
"=",
"re",
".",
"exec",
"(",
"str",
")",
")",
"{",
"// Get the delimiter that was found.",
"var",
"matchedDelim",
"=",
"match",
"[",
"1",
"]",
";",
"// Check to see if the given delimiter has a length",
"// (is not the start of string) and if it matches",
"// field delimiter. If it does not, then we can expect",
"// this delimiter to be a row delimiter.",
"if",
"(",
"matchedDelim",
".",
"length",
"&&",
"(",
"matchedDelim",
"!=",
"opts",
".",
"delim",
")",
")",
"{",
"// Since we have reached a new row of data,",
"// add an empty row to our data array.",
"arr",
".",
"push",
"(",
"[",
"]",
")",
";",
"}",
"// Now that we have our delimiter out of the way,",
"// let's check to see which kind of value we",
"// captured (quoted or unquoted).",
"if",
"(",
"match",
"[",
"2",
"]",
")",
"{",
"// We found a quoted value. When we capture",
"// this value, unescape any double quotes.",
"value",
"=",
"match",
"[",
"2",
"]",
".",
"replace",
"(",
"/",
"\"\"",
"/",
"g",
",",
"'\"'",
")",
";",
"}",
"else",
"{",
"// We found a non-quoted value.",
"value",
"=",
"match",
"[",
"3",
"]",
";",
"}",
"// Now that we have our value string, let's add",
"// it to the data array.",
"arr",
"[",
"arr",
".",
"length",
"-",
"1",
"]",
".",
"push",
"(",
"value",
")",
";",
"}",
"// Return the parsed data.",
"return",
"arr",
";",
"}"
] | Parse a delimited string into an array of arrays.
The default delimiter is `comma`, this can be
overriden by passed a different delimiter on
the `delim` option as a second argument.
This Function is from [Ben Nadel] by way of [Mr Data Converer]
@param {String} `str`
@param {Object} `options`
@return {Array} | [
"Parse",
"a",
"delimited",
"string",
"into",
"an",
"array",
"of",
"arrays",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/parser.js#L205-L266 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.