<commit_before>/*jshint esversion: 6 */

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({
	origin: true
});
const googleMapsClient = require('@google/maps').createClient({
  key: functions.config().keys.googlemaps
});
admin.initializeApp(functions.config().firebase);

/* Begin Functions */

//Get Nearby Places
exports.getNearbyPlacesLegacy = functions.https.onRequest((request, response) => {

  const latitude = request.body.latitude;
  const longitude = request.body.longitude;
  var limit = request.body.limit;
  var page = request.body.limit;

  cors(request, response, () => {

    if (latitude === undefined || latitude === null) {
      response.status(400).send("Latitude can't be null or undefined");
    }
    if (longitude === undefined || longitude === null) {
      response.status(400).send("Longitude can't be null or undefined");
    }
    if (limit === undefined || limit === null) {
      limit = 100;
    }
    if (page === undefined || page === null) {
      page = 0;
    }

		var places = {};
    admin.database().ref().child('COL/BOGOTA/TRAFFICLIGHTS').limitToFirst(1).once('value', function (snapshotTF) {
        if (snapshotTF.val() !== undefined) {
					for (var key in snapshotTF.val()) {
      			if (snapshotTF.val().hasOwnProperty(key)) {
							places[key] = snapshotTF.val()[key];
      			}
    			}
					admin.database().ref().child('COL/BOGOTA/FOOD').limitToFirst(1).once('value', function (snapshotFD) {
			        if (snapshotFD.val() !== undefined) {
								for (var key in snapshotFD.val()) {
			      			if (snapshotFD.val().hasOwnProperty(key)) {
										places[key] = snapshotFD.val()[key];
			      			}
			    			}
								admin.database().ref().child('COL/BOGOTA/CULTURE').limitToFirst(1).once('value', function (snapshotCT) {
						        if (snapshotCT.val() !== undefined) {
											for (var key in snapshotCT.val()) {
						      			if (snapshotCT.val().hasOwnProperty(key)) {
													places[key] = snapshotCT.val()[key];
						      			}
						    			}
											admin.database().ref().child('COL/BOGOTA/HEALTH').limitToFirst(1).once('value', function (snapshotHT) {
									        if (snapshotHT.val() !== undefined) {
														for (var key in snapshotHT.val()) {
									      			if (snapshotHT.val().hasOwnProperty(key)) {
																places[key] = snapshotHT.val()[key];
									      			}
									    			}
														admin.database().ref().child('COL/BOGOTA/STORE').limitToFirst(1).once('value', function (snapshotST) {
												        if (snapshotST.val() !== undefined) {
																	for (var key in snapshotST.val()) {
												      			if (snapshotST.val().hasOwnProperty(key)) {
																			places[key] = snapshotST.val()[key];
												      			}
												    			}
																	admin.database().ref().child('COL/BOGOTA/SECURITY').limitToFirst(1).once('value', function (snapshotSC) {
															        if (snapshotSC.val() !== undefined) {
																				for (var key in snapshotSC.val()) {
															      			if (snapshotSC.val().hasOwnProperty(key)) {
																						places[key] = snapshotSC.val()[key];
															      			}
															    			}

															          response.status(200).send(places);
															        } else {
															          response.status(400).send("Places not found");
															        }
															    });
												        } else {
												          response.status(400).send("Places not found");
												        }
												    });
									        } else {
									          response.status(400).send("Places not found");
									        }
									    });
						        } else {
						          response.status(400).send("Places not found");
						        }
						    });
			        } else {
			          response.status(400).send("Places not found");
			        }
			    });
        } else {
          response.status(400).send("Places not found");
        }
    });
  });

});

exports.getNearbyPlaces = functions.https.onRequest((request, response) => {

  const latitude = request.body.latitude;
  const longitude = request.body.longitude;

  cors(request, response, () => {

    if (latitude === undefined || latitude === null) {
      response.status(400).send("Latitude can't be null or undefined");
    }
    if (longitude === undefined || longitude === null) {
      response.status(400).send("Longitude can't be null or undefined");
    }
		googleMapsClient.placesNearby({
      language: 'es',
      location: [latitude, longitude],
      radius: 150
    }, function(err, responseGoogle) {
  		if (!err) {
    		response.status(200).send(getPlacesForGooglePlaces(responseGoogle.json.results, latitude, longitude));
  		} else {
				response.status(500).send(err);
			}
		});
  });

});

function getPlacesForGooglePlaces(googleResults, latitude, longitude) {

	var places  = {};

	for (let googlePlace of googleResults) {

		if (getDistanceFromLatLonInKm(latitude, longitude,googlePlace.geometry.location.lat, googlePlace.geometry.location.lng) > 0.15) {
			continue;
		}

		var newPlace = {};

		newPlace.name = googlePlace.name;
		newPlace.address = googlePlace.vicinity;
		newPlace.latitude = googlePlace.geometry.location.lat;
		newPlace.longitude = googlePlace.geometry.location.lng;
		newPlace.type = googlePlace.types[0];
		newPlace.pinType = getGooglePlacePinTypeAndThumbnail(googlePlace).pinType;
		newPlace.thumbnailURL = getGooglePlacePinTypeAndThumbnail(googlePlace).thumbnailURL;

		places[googlePlace.id] = newPlace;
	}

	return places;

}

function getGooglePlacePinTypeAndThumbnail(googlePlace) {
	var result = {};

	switch (googlePlace.types[0]) {

		case "airport":
		case "bus_station":
		case "car_dealer":
		case "car_rental":
		case "car_repair":
		case "car_wash":
		case "gas_station":
		case "lodging":
		case "moving_company":
		case "parking":
		case "post_office":
		case "subway_station":
		case "taxi_stand":
		case "train_station":
		case "transit_station":
		case "travel_agency":
		case "intersection":
			result.pinType = "TRANSPORT";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FTransport%2Fcar-2.png?alt=media";
			break;

		case "amusement_park":
		case "aquarium":
		case "art_gallery":
		case "campground":
		case "cemetery":
		case "church":
		case "city_hall":
		case "courthouse":
		case "embassy":
		case "hindu_temple":
		case "local_government_office":
		case "mosque":
		case "movie_theater":
		case "museum":
		case "night_club":
		case "park":
		case "place_of_worship":
		case "rv_park":
		case "stadium":
		case "synagogue":
		case "zoo":
		case "natural_feature":
		case "point_of_interest":
			result.pinType = "CULTURE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FCulture%2Ftheater.png?alt=media";
			break;

		case "atm":
		case "bank":
		case "accounting":
		case "casino":
		case "finance":
		case "insurance_agency":
			result.pinType = "STORE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FMoney%2Fpayment.png?alt=media";
			break;

		case "bakery":
		case "cafe":
		case "grocery_or_supermarket":
		case "food":
		case "liquor_store":
		case "meal_delivery":
		case "meal_takeaway":
		case "restaurant":
			result.pinType = "FOOD";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FFood%2Fwine-bottle.png?alt=media";
			break;

		case "bar":
		case "beauty_salon":
		case "book_store":
		case "bowling_alley":
		case "bicycle_store":
		case "clothing_store":
		case "convenience_store":
		case "department_store":
		case "electrician":
		case "electronics_store":
		case "establishment":
		case "florist":
		case "funeral_home":
		case "furniture_store":
		case "general_contractor":
		case "hair_care":
		case "hardware_store":
		case "home_goods_store":
		case "jewelry_store":
		case "laundry":
		case "lawyer":
		case "locksmith":
		case "movie_rental":
		case "painter":
		case "pet_store":
		case "plumber":
		case "real_estate_agency":
		case "roofing_contractor":
		case "shoe_store":
		case "shopping_mall":
		case "spa":
		case "storage":
		case "store":
		case "veterinary_care":
			result.pinType = "STORE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FStore%2Fstore-2.png?alt=media";
			break;

		case "dentist":
		case "doctor":
		case "gym":
		case "health":
		case "hospital":
		case "pharmacy":
		case "physiotherapist":
			result.pinType = "HEALTH";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FHealth%2Fhospital.png?alt=media";
			break;

		case "fire_station":
		case "police":
			result.pinType = "SECURITY";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FSecurity%2Fpolice.png?alt=media";
			break;

		case "library":
		case "school":
		case "university":
			result.pinType = "EDUCATION";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FEducation%2Flibrary.png?alt=media";
			break;

		default:
			result.pinType = "OTHER";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FDefault%2Fmap.png?alt=media";
	}

	return result;
}

//Add new Place to Database
exports.addPlace = functions.https.onRequest((request, response) => {

  const idToken = request.body.idToken;

  const name = request.body.name;
  const type = request.body.type;
  const latitude = request.body.latitude;
  const longitude = request.body.longitude;
  const thumbnailURL = request.body.thumbnailURL;

  cors(request, response, () => {

    // if (idToken === undefined || idToken === null) {
    //   response.status(400).send("Token can't be null or undefined");
    // }

    // admin.auth().verifyIdToken(idToken).then(function (decodedToken) {
      // var uid = decodedToken.uid;
      // if (uid.localeCompare(functions.config().admin.uid) === 0) {

        if (name === undefined || name === null) {
          response.status(400).send("Name can't be null or undefined");
        }
        if (type === undefined || type === null) {
          response.status(400).send("Type can't be null or undefined");
        }
        if (latitude === undefined || latitude === null) {
          response.status(400).send("Latitude can't be null or undefined");
        }
        if (longitude === undefined || longitude === null) {
          response.status(400).send("Longitude can't be null or undefined");
        }
        if (thumbnailURL === undefined || thumbnailURL === null) {
          response.status(400).send("Thumbnail URL can't be null or undefined");
        }

        admin.database().ref("places").push().set({
          name: name,
          latitude: latitude,
          longitude: longitude,
          thumbnailURL: thumbnailURL
        }).then(function (snapshot) {
          response.status(200).send("Place Created");
        });

      // } else {
      //   response.status(401).send("Unauthorized");
      // }

    // }).catch(function (error) {
    //   console.log(error);
    //   response.status(401).send("Unauthorized: Invalid Token");
    // });

  });

});

//Get Current Security Level for Location
exports.getCurrentLocationSecurity = functions.https.onRequest((request, response) => {

  const latitude = request.body.latitude;
  const longitude = request.body.longitude;

  cors(request, response, () => {

    if (latitude === undefined || latitude === null) {
      response.status(400).send("Latitude can't be null or undefined");
    }
    if (longitude === undefined || longitude === null) {
      response.status(400).send("Longitude can't be null or undefined");
    }

    const jsonSecurityDetail = {
      dangerLevel:"No Peligroso"
    };

    response.status(200).send(jsonSecurityDetail);

  });

});

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180);
}

/* End Functions */
<commit_msg>Added Elevation<commit_after>/*jshint esversion: 6 */

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({
	origin: true
});
const googleMapsClient = require('@google/maps').createClient({
  key: functions.config().keys.googlemaps
});
admin.initializeApp(functions.config().firebase);

/* Begin Functions */
exports.getNearbyPlaces = functions.https.onRequest((request, response) => {

  const latitude = request.body.latitude;
  const longitude = request.body.longitude;

  cors(request, response, () => {

    if (latitude === undefined || latitude === null) {
      response.status(400).send("Latitude can't be null or undefined");
    }
    if (longitude === undefined || longitude === null) {
      response.status(400).send("Longitude can't be null or undefined");
    }
		googleMapsClient.placesNearby({
      language: 'es',
      location: [latitude, longitude],
      radius: 150
    }, function(err, responseGoogle) {
  		if (!err) {
				getPlacesForGooglePlaces(responseGoogle.json.results, latitude, longitude, function(places) {
					response.status(200).send(places);
				});
  		} else {
				response.status(500).send(err);
			}
		});
  });

});

function getPlacesForGooglePlaces(googleResults, latitude, longitude, callback) {

	var places  = {};
	var placesIds = [];
	var placesCoordinates = [];

	var index = 0;
	for (let googlePlace of googleResults) {

		if (getDistanceFromLatLonInKm(latitude, longitude,googlePlace.geometry.location.lat, googlePlace.geometry.location.lng) > 0.15) {
			continue;
		}

		var newPlace = {};

		newPlace.name = googlePlace.name;
		newPlace.address = googlePlace.vicinity;
		newPlace.latitude = googlePlace.geometry.location.lat;
		newPlace.longitude = googlePlace.geometry.location.lng;
		newPlace.type = googlePlace.types[0];
		newPlace.pinType = getGooglePlacePinTypeAndThumbnail(googlePlace).pinType;
		newPlace.thumbnailURL = getGooglePlacePinTypeAndThumbnail(googlePlace).thumbnailURL;
		newPlace.serverIndex = index;

		places[googlePlace.id] = newPlace;

		placesIds.push(googlePlace.id);
		placesCoordinates.push({
    	lat: googlePlace.geometry.location.lat,
    	lng: googlePlace.geometry.location.lng
  	});
		index++;
	}

	getAltitudeForLatLongCoordinates(placesCoordinates, function(resultAltitudes) {
		if (resultAltitudes !== undefined) {

			for (placeKey in places) {
				if (places.hasOwnProperty(placeKey)) {
					places[placeKey].elevation = resultAltitudes[places[placeKey].serverIndex]["elevation"];
				}
			}

			console.log("Proccesed Places", places);
			callback(places);
		}
	});
}

function getAltitudeForLatLongCoordinates(locations, callback) {
	googleMapsClient.elevation({
      locations: locations
    }, (err, response) => {
      if (err) {
				console.log("Got ElevationAPI Error", err);
				callback(undefined);
			} else {
				callback(response.json.results);
			}
  });
}

function getGooglePlacePinTypeAndThumbnail(googlePlace) {
	var result = {};

	switch (googlePlace.types[0]) {

		case "airport":
		case "bus_station":
		case "car_dealer":
		case "car_rental":
		case "car_repair":
		case "car_wash":
		case "gas_station":
		case "lodging":
		case "moving_company":
		case "parking":
		case "post_office":
		case "subway_station":
		case "taxi_stand":
		case "train_station":
		case "transit_station":
		case "travel_agency":
		case "intersection":
			result.pinType = "TRANSPORT";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FTransport%2Fcar-2.png?alt=media";
			break;

		case "amusement_park":
		case "aquarium":
		case "art_gallery":
		case "campground":
		case "cemetery":
		case "church":
		case "city_hall":
		case "courthouse":
		case "embassy":
		case "hindu_temple":
		case "local_government_office":
		case "mosque":
		case "movie_theater":
		case "museum":
		case "night_club":
		case "park":
		case "place_of_worship":
		case "rv_park":
		case "stadium":
		case "synagogue":
		case "zoo":
		case "natural_feature":
		case "point_of_interest":
			result.pinType = "CULTURE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FCulture%2Ftheater.png?alt=media";
			break;

		case "atm":
		case "bank":
		case "accounting":
		case "casino":
		case "finance":
		case "insurance_agency":
			result.pinType = "STORE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FMoney%2Fpayment.png?alt=media";
			break;

		case "bakery":
		case "cafe":
		case "grocery_or_supermarket":
		case "food":
		case "liquor_store":
		case "meal_delivery":
		case "meal_takeaway":
		case "restaurant":
			result.pinType = "FOOD";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FFood%2Fwine-bottle.png?alt=media";
			break;

		case "bar":
		case "beauty_salon":
		case "book_store":
		case "bowling_alley":
		case "bicycle_store":
		case "clothing_store":
		case "convenience_store":
		case "department_store":
		case "electrician":
		case "electronics_store":
		case "establishment":
		case "florist":
		case "funeral_home":
		case "furniture_store":
		case "general_contractor":
		case "hair_care":
		case "hardware_store":
		case "home_goods_store":
		case "jewelry_store":
		case "laundry":
		case "lawyer":
		case "locksmith":
		case "movie_rental":
		case "painter":
		case "pet_store":
		case "plumber":
		case "real_estate_agency":
		case "roofing_contractor":
		case "shoe_store":
		case "shopping_mall":
		case "spa":
		case "storage":
		case "store":
		case "veterinary_care":
			result.pinType = "STORE";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FStore%2Fstore-2.png?alt=media";
			break;

		case "dentist":
		case "doctor":
		case "gym":
		case "health":
		case "hospital":
		case "pharmacy":
		case "physiotherapist":
			result.pinType = "HEALTH";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FHealth%2Fhospital.png?alt=media";
			break;

		case "fire_station":
		case "police":
			result.pinType = "SECURITY";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FSecurity%2Fpolice.png?alt=media";
			break;

		case "library":
		case "school":
		case "university":
			result.pinType = "EDUCATION";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FEducation%2Flibrary.png?alt=media";
			break;

		default:
			result.pinType = "OTHER";
			result.thumbnailURL = "https://firebasestorage.googleapis.com/v0/b/vhistaapp.appspot.com/o/Vhista-GPS%2FDefaults%2FPlacesTypes%2FDefault%2Fmap.png?alt=media";
	}

	return result;
}

//Get Current Security Level for Location
exports.getCurrentLocationSecurity = functions.https.onRequest((request, response) => {

  const latitude = request.body.latitude;
  const longitude = request.body.longitude;

  cors(request, response, () => {

    if (latitude === undefined || latitude === null) {
      response.status(400).send("Latitude can't be null or undefined");
    }
    if (longitude === undefined || longitude === null) {
      response.status(400).send("Longitude can't be null or undefined");
    }
    const jsonSecurityDetail = {
      dangerLevel:"No Peligroso"
    };
    response.status(200).send(jsonSecurityDetail);

  });

});

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180);
}

/* End Functions */
<|endoftext|>


<commit_before>var Higgins = function () {};

var pantry = require('pantry');

Higgins.prototype.newsPlease = function (url, feedType, clear) {
  pantry.configure({
    maxLife: 600,
    parser: 'xml'
  });

  pantry.fetch({
    uri: url
  }, function (error, data) {
    console.log('Fetching: ' + url);
    if (error) {
      console.log('pantry error: ' + error);
    }
    return JSON.stringify(data, null, '  ');
//    res.write(JSON.stringify(data, null, '  '));
//    res.end();
  });

};

module.exports = new Higgins();<commit_msg>added callback<commit_after>var Higgins = function () {};

var pantry = require('pantry');

Higgins.prototype.newsPlease = function (url, feedType, clear, callback) {
  pantry.configure({
    maxLife: 600,
    parser: 'xml'
  });

  pantry.fetch({
    uri: url
  }, function (error, data) {
    console.log('Fetching: ' + url);
    if (error) {
      console.log('pantry error: ' + error);
    }
    // return JSON.stringify(data, null, '  ');
    return callback(JSON.stringify(data, null, '  '));
//    res.write(JSON.stringify(data, null, '  '));
//    res.end();
  });

};

module.exports = new Higgins();
<|endoftext|>


<commit_before>var Board = (function () {
	"use strict";

	var board = {
		player:    null,
		available: {}, // {'Copper': 10,}
		trashed:   {},
		visible:   {},

		init: function (cards) {
			this.player = Player; // use single Player object
			this.cards  = Cards;

			if (!cards instanceof Array || cards.length !== 10) {
				throw "Not enough cards passed to the Board initializer";
			}

			//initialize the board collection with the treasure, victory and action cards
			//todo check the rules for more details
		},
		reset: function () {
			this.visible   = [];
			this.trashed   = [];
			this.available = [];
		},
		clear: function () {
			this.visible = [];
		},
		buy: function (card) {
			if (this.buyPossible(card)) {
				this.player.takeCoins(Cards[card].cost);
				this.player.takeBuyPoints();

				//take the card off the supply unless it's an infinite one - treasure
				return true;
			}

			return false;
		},
		buyPossible: function (card) {
			return this.cards[card].cost <= this.player.coins() && this.player.buys() > 0;
		}
	};

	return board;
}());<commit_msg>Fix tabs<commit_after>var Board = (function () {
  "use strict";

  var board = {
    player:    null,
    available: {}, // {'Copper': 10,}
    trashed:   {},
    visible:   {},

    init: function (cards) {
      this.player = Player; // use single Player object
      this.cards  = Cards;

      if (!cards instanceof Array || cards.length !== 10) {
        throw "Not enough cards passed to the Board initializer";
      }

      //initialize the board collection with the treasure, victory and action cards
      //todo check the rules for more details
    },
    reset: function () {
      this.visible   = [];
      this.trashed   = [];
      this.available = [];
    },
    clear: function () {
      this.visible = [];
    },
    buy: function (card) {
      if (this.buyPossible(card)) {
        this.player.takeCoins(Cards[card].cost);
        this.player.takeBuyPoints();

        //take the card off the supply unless it's an infinite one - treasure
        return true;
      }

      return false;
    },
    buyPossible: function (card) {
      return this.cards[card].cost <= this.player.coins() && this.player.buys() > 0;
    }
  };

  return board;
}());
<|endoftext|>


<commit_before>'use strict';

var MODULE_NAME = 'bons.bShape';

var angular = require('angular');

var bCircle = require('./shapes/b-circle');

angular .module(MODULE_NAME, [])
        .directive('bShape',[
          function()
          {

            return {
              restrict: "A",
              transclude: true,
              controller: function()
              {
                var self = this;

                self.createCircle = function(canvas, args)
                {
                  return new bCircle(canvas, args);
                };
              },
              link: function(scope, elem, attr, ctrl, trans)
              {
                //avoid using this directive in another element than a canvas
                if(elem[0].tagName.toLowerCase() !== 'canvas')
                {
                  console.error("Directive bShape must be used in a canvas");
                  return;
                }

                switch(attr.type)
                {
                  default:
                    scope.shape = ctrl.createCircle(elem, {
                      percent: attr.percent,
                      radius: attr.radius,
                      stroke: attr.stroke,
                      gradientStart: attr.gradientStart,
                      gradientMiddle: attr.gradientMiddle,
                      gradientEnd: attr.gradientEnd,
                    });
                    break;
                }

                scope.shape.drawWithAnimation();
                // manually transclusion appending this scope
                trans(scope, function(clone)
                {
                  elem.append(clone);
                });
              }
            };
          }
        ]);

module.exports = MODULE_NAME;
<commit_msg>added events<commit_after>'use strict';

var MODULE_NAME = 'bons.bShape';

var angular = require('angular');

var bCircle = require('./shapes/b-circle');

angular .module(MODULE_NAME, [])
        .directive('bShape',[
          function()
          {

            return {
              restrict: "A",
              transclude: true,
              controller: function()
              {
                var self = this;

                self.createCircle = function(canvas, args)
                {
                  self.shape = new bCircle(canvas, args);
                };
              },
              link: function(scope, elem, attr, ctrl, trans)
              {
                //avoid using this directive in another element than a canvas
                if(elem[0].tagName.toLowerCase() !== 'canvas')
                {
                  console.error("Directive bShape must be used in a canvas");
                  return;
                }

                switch(attr.type)
                {
                  default:
                    ctrl.createCircle(elem, {
                      percent: attr.percent,
                      radius: attr.radius,
                      stroke: attr.stroke,
                      gradientStart: attr.gradientStart,
                      gradientMiddle: attr.gradientMiddle,
                      gradientEnd: attr.gradientEnd,
                    });
                    break;
                }

                if(attr.autoload)
                {
                  ctrl.shape.drawWithAnimation();
                }

                scope.$on("bShape.drawWithAnimation", function()
                {
                  ctrl.shape.drawWithAnimation();
                });
                scope.$on("bShape.draw", function()
                {
                  ctrl.shape.draw();
                });
                // manually transclusion appending this scope
                trans(scope, function(clone)
                {
                  elem.append(clone);
                });
              }
            };
          }
        ]);

module.exports = MODULE_NAME;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const nsIScriptError = Ci.nsIScriptError;

const WARNING_FLAG = nsIScriptError.warningFlag;

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const urlRe = new RegExp("([^:]*):(//)?([^/]*)");
const reUncaught = /uncaught exception/;
const reException = /uncaught exception:\s\[Exception...\s\"([^\"]*)\".*nsresult:.*\(([^\)]*)\).*location:\s\"([^\s]*)\sLine:\s(\d*)\"/;
const statusBar = $("fbStatusBar");
const statusText = $("fbStatusText");

const pointlessErrors =
{
    "uncaught exception: Permission denied to call method Location.toString": 1,
    "uncaught exception: Permission denied to get property Window.writeDebug": 1,
    "uncaught exception: Permission denied to get property XULElement.accessKey": 1,
    "this.docShell has no properties": 1,
    "aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation).currentURI has no properties": 1,
    "Deprecated property window.title used. Please use document.title instead.": 1,
    "Key event not available on GTK2:": 1
};

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const fbs = Cc["@joehewitt.com/firebug;1"].getService().wrappedJSObject;
const consoleService = CCSV("@mozilla.org/consoleservice;1", "nsIConsoleService");

// ************************************************************************************************

var Errors = Firebug.Errors = extend(Firebug.Module,
{
    clear: function(context)
    {
        this.setCount(context, 0)
    },

    increaseCount: function(context)
    {
        this.setCount(context, context.errorCount + 1)
    },

    setCount: function(context, count)
    {
        context.errorCount = count;

        if (context == FirebugContext)
            this.showCount(context.errorCount);
    },

    showMessageOnStatusBar: function(error)
    {
        if (statusText && statusBar && Firebug.breakOnErrors && error.message &&  !(error.flags & nsIScriptError.WARNING_FLAG))  // sometimes statusText is undefined..how?
        {
            statusText.setAttribute("value", error.message);
            statusBar.setAttribute("errors", "true");
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.showMessageOnStatusBar error.message:"+error.message+"\n"); /*@explore*/
        }
    },

    showCount: function(errorCount)
    {
        if (!statusBar)
            return;

        if (errorCount)
        {
            if (Firebug.showErrorCount)
            {
                var errorLabel = errorCount > 1
                    ? $STRF("ErrorsCount", [errorCount])
                    : $STRF("ErrorCount", [errorCount]);

                statusText.setAttribute("value", errorLabel);
            }

            statusBar.setAttribute("errors", "true");
        }
        else
        {
            statusText.setAttribute("value", "");
            statusBar.removeAttribute("errors");
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // Called by Console

    startObserving: function()
    {
        consoleService.registerListener(this);
        $('fbStatusIcon').setAttribute("errors", "on");

        if (statusBar)
            statusBar.setAttribute("disabled", "true");

    },

    stopObserving: function()
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("errors.disable unregisterListener\n");
        consoleService.unregisterListener(this);
         $('fbStatusIcon').removeAttribute("errors");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // extends ConsoleObserver

    observe: function(object)
    {
        try
        {
            var context = null;
            if (FirebugContext)
                context = FirebugContext;

            if (FBTrace.DBG_ERRORS && !FirebugContext)
                FBTrace.sysout("errors.observe, no FirebugContext in "+window.location+"\n");

            var isWarning = object.flags & WARNING_FLAG;

            if (object instanceof nsIScriptError)
            {
                this.logScriptError(context, object, isWarning);
            }
            else
            {
                if (Firebug.showChromeMessages)
                {
                    if (lessTalkMoreAction(context, object, isWarning))
                        return;
                    if (FBTrace.DBG_ERRORS)                                                                               /*@explore*/
                        FBTrace.dumpProperties("errors.observe showChromeMessages message:", object);             /*@explore*/

                    if (context) // Must be an nsIConsoleMessage
                        Firebug.Console.log(object.message, context, "consoleMessage", FirebugReps.Text);
                    else
                    {
                        if (FBTrace.DBG_ERRORS)
                            FBTrace.dumpProperties("errors.observe, no context for message, FirebugContext:", FirebugContext);
                        return;
                    }
                }
                else
                {
                    if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
                        FBTrace.dumpProperties("errors.observe showChromeMessages off, dropped:", object);                                 /*@explore*/
                    return;
                }
            }
            if (FBTrace.DBG_ERRORS)
            {
                if (context.window)
                    FBTrace.sysout("error logged to ",  context.window.location+"\n");
                else
                {
                    FBTrace.dumpProperties("errors.observe, context with no window, error object:", object);
                    FBTrace.dumpStack("errors.observe, context with no window");
                }
            }
        }
        catch (exc)
        {
            // Errors prior to console init will come out here, eg error message from Firefox startup jjb.
            if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
                FBTrace.dumpProperties("errors.observe FAILS", exc);                                                   /*@explore*/
        }
    },

    logScriptError: function(context, object, isWarning)
    {
        if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
            FBTrace.dumpProperties("errors.observe logScriptError "+(Firebug.errorStackTrace?"have ":"NO ")+"errorStackTrace error object:", object);/*@explore*/

        var category = getBaseCategory(object.category);
        var isJSError = category == "js" && !isWarning;

        var errorContext = getErrorContext(object);
        if (FBTrace.DBG_ERRORS && !errorContext)
                FBTrace.sysout("errors.observe no context from error filename\n");
        if (errorContext)
            context = errorContext;

        if (lessTalkMoreAction(context, object, isWarning))
            return;

        if (!isWarning)
            this.increaseCount(context);

        if (isJSError && Firebug.showStackTrace)
        {
            var trace = Firebug.errorStackTrace;
            if (trace)
                correctLineNumbersWithStack(trace, object);
        }
        else if (checkForUncaughtException(context, object))
        {
            context = getExceptionContext(context);
            correctLineNumbersOnExceptions(context, object);
        }

        Firebug.errorStackTrace = null;  // clear global: either we copied it or we don't use it.
        context.thrownStackTrace = null;

        var error = new ErrorMessage(object.errorMessage, object.sourceName,
            object.lineNumber, object.sourceLine, category, context, trace);  // the sourceLine will cause the source to be loaded.

        var className = isWarning ? "warningMessage" : "errorMessage";

        if (context) // then report later to avoid loading sourceS
            context.throttle(Firebug.Console.log, Firebug.Console, [error, context,  className, false, true], true);
        else
            Firebug.Console.log(error, context,  className);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // extends Module

    initContext: function(context)
    {
        context.errorCount = 0;
    },

    showContext: function(browser, context)
    {
        if (statusBar)
            statusBar.setAttribute("disabled", !context);

        this.showCount(context ? context.errorCount : 0);
    }
});

// ************************************************************************************************
// Local Helpers

const categoryMap =
{
    "javascript": "js",
    "JavaScript": "js",
    "DOM": "js",
    "Events": "js",
    "CSS": "css",
    "XML": "xml",
    "malformed-xml": "xml"
};

function getBaseCategory(categories)
{
    var categoryList = categories.split(" ");
    for (var i = 0 ; i < categoryList.length; ++i)
    {
        var category = categoryList[i];
        if ( categoryMap.hasOwnProperty(category) )
            return categoryMap[category];
    }
}

function categoryFilter(url, category, isWarning)
{
    var m = urlRe.exec(url);
    var errorScheme = m ? m[1] : "";
    if (errorScheme == "javascript")
        return true;

    var isChrome = false;

    var categories = category.split(" ");
    for (var i = 0 ; i < categories.length; ++i)
    {
        var category = categories[i];
        if (category == "CSS" && !Firebug.showCSSErrors)
            return false;
        else if ((category == "XML" || category == "malformed-xml" ) && !Firebug.showXMLErrors)
            return false;
        else if ((category == "javascript" || category == "JavaScript" || category == "DOM")
                    && !isWarning && !Firebug.showJSErrors)
            return false;
        else if ((category == "javascript" || category == "JavaScript" || category == "DOM")
                    && isWarning && !Firebug.showJSWarnings)
            return false;
        else if (errorScheme == "chrome" || category == "XUL" || category == "chrome" || category == "XBL"
                || category == "component")
            isChrome = true;
    }

    if ((isChrome && !Firebug.showChromeErrors))
        return false;

    return true;
}

function domainFilter(url)  // never called?
{
    if (Firebug.showExternalErrors)
        return true;

    var browserWin = document.getElementById("content").contentWindow;

    var m = urlRe.exec(browserWin.location.href);
    if (!m)
        return false;

    var browserDomain = m[3];

    m = urlRe.exec(url);
    if (!m)
        return false;

    var errorScheme = m[1];
    var errorDomain = m[3];

    return errorScheme == "javascript"
        || errorScheme == "chrome"
        || errorDomain == browserDomain;
}

function lessTalkMoreAction(context, object, isWarning)
{
    if (!context || !categoryFilter(object.sourceName, object.category, isWarning))
    {
        if (FBTrace.DBG_ERRORS)
        {                                                         /*@explore*/
            FBTrace.sysout("errors.observe dropping "+object.category+(context?" categoryFilter:"+categoryFilter(object.sourceName, object.category, isWarning):" no context")+"\n");           /*@explore*/
        }
        return true;
    }

    for (var msg in pointlessErrors)
    {
        if(msg.charAt(0) == object.errorMessage.charAt(0))
        {
            if (object.errorMessage.indexOf(msg) == 0)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("errors.observe dropping pointlessError: "+msg+"\n");
                return true;
            }
        }
    }

    var msgId = [object.errorMessage, object.sourceName, object.lineNumber].join("/");
    if (context.errorMap && msgId in context.errorMap)
    {
        context.errorMap[msgId] += 1;
        if (FBTrace.DBG_ERRORS)                                                                             /*@explore*/
            FBTrace.sysout("errors.observe dropping duplicate msg count:"+context.errorMap[msgId]+"\n");             /*@explore*/
        return true;
    }

    if (!context.errorMap)
        context.errorMap = {};

    context.errorMap[msgId] = 1;
}

function getErrorContext(object)
{
    var errorContext = null;

    var url = object.sourceName;

    TabWatcher.iterateContexts(
        function findContextByURL(context)
        {
        FBTrace.sysout("errors.observe trying context "+context.window.location.toString()+"\n");
            if (context.window.location.toString() == url)
                return errorContext = context;
            else
            {
                if (context.sourceFileMap && context.sourceFileMap[url])
                    return errorContext = context;
            }
        }
    );

    return errorContext; // we looked everywhere...
}

function checkForUncaughtException(context, object)
{
    if (object.flags & object.exceptionFlag)
    {
        if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe is exception\n");
        if (reUncaught.test(object.errorMessage))
        {
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("uncaught exception matches "+reUncaught+"\n");
            if (context.thrownStackTrace)
            {
                Firebug.errorStackTrace = context.thrownStackTrace;
                return true;
                if (FBTrace.DBG_ERRORS) FBTrace.dumpProperties("errors.observe trace.frames", context.thrownStackTrace.frames);
            }
            else
            {
                 if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe NO context.thrownStackTrace\n");
            }
        }
        else
        {
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe not an uncaught exception\n");
        }
    }
    return false;
}

function getExceptionContext(context)
{
    var errorWin = fbs.lastErrorWindow;  // not available unless Script panel is enabled.
    if (errorWin)
    {
        var errorContext = TabWatcher.getContextByWindow(errorWin);
        if (FBTrace.DBG_ERRORS)                                                                    /*@explore*/
            FBTrace.sysout("errors.observe exception context:"+errorContext+" errorWin"+errorWin+"\n");           /*@explore*/
        return errorContext;
    }
    return context;
}

function correctLineNumbersOnExceptions(context, object)
{
    var m = reException.exec(object.errorMessage);
    if (m)
    {
        var exception = m[1];
        if (exception)
            errorMessage = "uncaught exception: "+exception;
        var nsresult = m[2];
        if (nsresult)
            errorMessage += " ("+nsresult+")";
        sourceName = m[3];
        lineNumber = m[4];

        var correctedError = object.init(errorMessage, sourceName, object.sourceLine, lineNumber, object.columnNumber, object.flags, object.category);
    }
}

function correctLineNumbersWithStack(trace, object)
{
    if (FBTrace.DBG_ERRORS)                                                                            /*@explore*/
        FBTrace.dumpProperties("errors.observe showStackTrace trace frames:", trace.frames);                          /*@explore*/
    var stack_frame = trace.frames[0];
    if (stack_frame)
    {
        sourceName = stack_frame.href;
        lineNumber = stack_frame.lineNo;
    }
    var correctedError = object.init(object.errorMessage, sourceName, object.sourceLine,lineNumber, object.columnNumber, object.flags, object.category);
}

// ************************************************************************************************

Firebug.registerModule(Errors);

// ************************************************************************************************

}});
<commit_msg>Fix issue 723, JavaScript errors not shown in Firebug even when debugging is enabled; Refactor errors.js. again.<commit_after>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;
const nsIScriptError = Ci.nsIScriptError;

const WARNING_FLAG = nsIScriptError.warningFlag;

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const urlRe = new RegExp("([^:]*):(//)?([^/]*)");
const reUncaught = /uncaught exception/;
const reException = /uncaught exception:\s\[Exception...\s\"([^\"]*)\".*nsresult:.*\(([^\)]*)\).*location:\s\"([^\s]*)\sLine:\s(\d*)\"/;
const statusBar = $("fbStatusBar");
const statusText = $("fbStatusText");

const pointlessErrors =
{
    "uncaught exception: Permission denied to call method Location.toString": 1,
    "uncaught exception: Permission denied to get property Window.writeDebug": 1,
    "uncaught exception: Permission denied to get property XULElement.accessKey": 1,
    "this.docShell has no properties": 1,
    "aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation).currentURI has no properties": 1,
    "Deprecated property window.title used. Please use document.title instead.": 1,
    "Key event not available on GTK2:": 1
};

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

const fbs = Cc["@joehewitt.com/firebug;1"].getService().wrappedJSObject;
const consoleService = CCSV("@mozilla.org/consoleservice;1", "nsIConsoleService");

// ************************************************************************************************

var Errors = Firebug.Errors = extend(Firebug.Module,
{
    clear: function(context)
    {
        this.setCount(context, 0)
    },

    increaseCount: function(context)
    {
        this.setCount(context, context.errorCount + 1)
    },

    setCount: function(context, count)
    {
        context.errorCount = count;

        if (context == FirebugContext)
            this.showCount(context.errorCount);
    },

    showMessageOnStatusBar: function(error)
    {
        if (statusText && statusBar && Firebug.breakOnErrors && error.message &&  !(error.flags & nsIScriptError.WARNING_FLAG))  // sometimes statusText is undefined..how?
        {
            statusText.setAttribute("value", error.message);
            statusBar.setAttribute("errors", "true");
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.showMessageOnStatusBar error.message:"+error.message+"\n"); /*@explore*/
        }
    },

    showCount: function(errorCount)
    {
        if (!statusBar)
            return;

        if (errorCount)
        {
            if (Firebug.showErrorCount)
            {
                var errorLabel = errorCount > 1
                    ? $STRF("ErrorsCount", [errorCount])
                    : $STRF("ErrorCount", [errorCount]);

                statusText.setAttribute("value", errorLabel);
            }

            statusBar.setAttribute("errors", "true");
        }
        else
        {
            statusText.setAttribute("value", "");
            statusBar.removeAttribute("errors");
        }
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // Called by Console

    startObserving: function()
    {
        consoleService.registerListener(this);
        $('fbStatusIcon').setAttribute("errors", "on");

        if (statusBar)
            statusBar.setAttribute("disabled", "true");

    },

    stopObserving: function()
    {
        if (FBTrace.DBG_ERRORS)
            FBTrace.sysout("errors.disable unregisterListener\n");
        consoleService.unregisterListener(this);
         $('fbStatusIcon').removeAttribute("errors");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // extends ConsoleObserver

    observe: function(object)
    {
        try
        {
            var context = null;
            if (FirebugContext)
                context = FirebugContext;

            if (FBTrace.DBG_ERRORS && !FirebugContext)
                FBTrace.sysout("errors.observe, no FirebugContext in "+window.location+"\n");

            var isWarning = object.flags & WARNING_FLAG;

            if (object instanceof nsIScriptError)
            {
                this.logScriptError(context, object, isWarning);
            }
            else
            {
                if (Firebug.showChromeMessages)
                {
                    if (lessTalkMoreAction(context, object, isWarning))
                        return;
                    if (FBTrace.DBG_ERRORS)                                                                               /*@explore*/
                        FBTrace.dumpProperties("errors.observe showChromeMessages message:", object);             /*@explore*/

                    if (context) // Must be an nsIConsoleMessage
                        Firebug.Console.log(object.message, context, "consoleMessage", FirebugReps.Text);
                    else
                    {
                        if (FBTrace.DBG_ERRORS)
                            FBTrace.dumpProperties("errors.observe, no context for message, FirebugContext:", FirebugContext);
                        return;
                    }
                }
                else
                {
                    if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
                        FBTrace.dumpProperties("errors.observe showChromeMessages off, dropped:", object);                                 /*@explore*/
                    return;
                }
            }
            if (FBTrace.DBG_ERRORS)
            {
                if (context.window)
                    FBTrace.sysout("error logged to ",  context.window.location+"\n");
                else
                {
                    FBTrace.dumpProperties("errors.observe, context with no window, error object:", object);
                    FBTrace.dumpStack("errors.observe, context with no window");
                }
            }
        }
        catch (exc)
        {
            // Errors prior to console init will come out here, eg error message from Firefox startup jjb.
            if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
                FBTrace.dumpProperties("errors.observe FAILS", exc);                                                   /*@explore*/
        }
    },

    logScriptError: function(context, object, isWarning)
    {
        if (FBTrace.DBG_ERRORS)                                                                                /*@explore*/
            FBTrace.dumpProperties("errors.observe logScriptError "+(Firebug.errorStackTrace?"have ":"NO ")+"errorStackTrace error object:", object);/*@explore*/

        var category = getBaseCategory(object.category);
        var isJSError = category == "js" && !isWarning;

        var errorContext = getErrorContext(object);
        if (FBTrace.DBG_ERRORS && !errorContext)
                FBTrace.sysout("errors.observe no context from error filename\n");
        if (errorContext)
            context = errorContext;

        if (lessTalkMoreAction(context, object, isWarning))
            return;

        if (!isWarning)
            this.increaseCount(context);

        if (isJSError && Firebug.showStackTrace)
        {
            var trace = Firebug.errorStackTrace;
            if (trace)
                correctLineNumbersWithStack(trace, object);
        }
        else if (checkForUncaughtException(context, object))
        {
            context = getExceptionContext(context);
            correctLineNumbersOnExceptions(context, object);
        }

        Firebug.errorStackTrace = null;  // clear global: either we copied it or we don't use it.
        context.thrownStackTrace = null;

        var error = new ErrorMessage(object.errorMessage, object.sourceName,
            object.lineNumber, object.sourceLine, category, context, trace);  // the sourceLine will cause the source to be loaded.

        var className = isWarning ? "warningMessage" : "errorMessage";

        if (context) // then report later to avoid loading sourceS
            context.throttle(Firebug.Console.log, Firebug.Console, [error, context,  className, false, true], true);
        else
            Firebug.Console.log(error, context,  className);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    // extends Module

    initContext: function(context)
    {
        context.errorCount = 0;
    },

    showContext: function(browser, context)
    {
        if (statusBar)
            statusBar.setAttribute("disabled", !context);

        this.showCount(context ? context.errorCount : 0);
    }
});

// ************************************************************************************************
// Local Helpers

const categoryMap =
{
    "javascript": "js",
    "JavaScript": "js",
    "DOM": "js",
    "Events": "js",
    "CSS": "css",
    "XML": "xml",
    "malformed-xml": "xml"
};

function getBaseCategory(categories)
{
    var categoryList = categories.split(" ");
    for (var i = 0 ; i < categoryList.length; ++i)
    {
        var category = categoryList[i];
        if ( categoryMap.hasOwnProperty(category) )
            return categoryMap[category];
    }
}

function categoryFilter(url, category, isWarning)
{
    var m = urlRe.exec(url);
    var errorScheme = m ? m[1] : "";
    if (errorScheme == "javascript")
        return true;

    var isChrome = false;

    var categories = category.split(" ");
    for (var i = 0 ; i < categories.length; ++i)
    {
        var category = categories[i];
        if (category == "CSS" && !Firebug.showCSSErrors)
            return false;
        else if ((category == "XML" || category == "malformed-xml" ) && !Firebug.showXMLErrors)
            return false;
        else if ((category == "javascript" || category == "JavaScript" || category == "DOM")
                    && !isWarning && !Firebug.showJSErrors)
            return false;
        else if ((category == "javascript" || category == "JavaScript" || category == "DOM")
                    && isWarning && !Firebug.showJSWarnings)
            return false;
        else if (errorScheme == "chrome" || category == "XUL" || category == "chrome" || category == "XBL"
                || category == "component")
            isChrome = true;
    }

    if ((isChrome && !Firebug.showChromeErrors))
        return false;

    return true;
}

function domainFilter(url)  // never called?
{
    if (Firebug.showExternalErrors)
        return true;

    var browserWin = document.getElementById("content").contentWindow;

    var m = urlRe.exec(browserWin.location.href);
    if (!m)
        return false;

    var browserDomain = m[3];

    m = urlRe.exec(url);
    if (!m)
        return false;

    var errorScheme = m[1];
    var errorDomain = m[3];

    return errorScheme == "javascript"
        || errorScheme == "chrome"
        || errorDomain == browserDomain;
}

function lessTalkMoreAction(context, object, isWarning)
{
    if (!context || !categoryFilter(object.sourceName, object.category, isWarning))
    {
        if (FBTrace.DBG_ERRORS)
        {                                                         /*@explore*/
            FBTrace.sysout("errors.observe dropping "+object.category+(context?" categoryFilter:"+categoryFilter(object.sourceName, object.category, isWarning):" no context")+"\n");           /*@explore*/
        }
        return true;
    }

    for (var msg in pointlessErrors)
    {
        if(msg.charAt(0) == object.errorMessage.charAt(0))
        {
            if (object.errorMessage.indexOf(msg) == 0)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("errors.observe dropping pointlessError: "+msg+"\n");
                return true;
            }
        }
    }

    var msgId = [object.errorMessage, object.sourceName, object.lineNumber].join("/");
    if (context.errorMap && msgId in context.errorMap)
    {
        context.errorMap[msgId] += 1;
        if (FBTrace.DBG_ERRORS)                                                                             /*@explore*/
            FBTrace.sysout("errors.observe dropping duplicate msg count:"+context.errorMap[msgId]+"\n");             /*@explore*/
        return true;
    }

    if (!context.errorMap)
        context.errorMap = {};

    context.errorMap[msgId] = 1;
}

function getErrorContext(object)
{
    var errorContext = null;

    var url = object.sourceName;

    TabWatcher.iterateContexts(
        function findContextByURL(context)
        {
            if (context.window.location.toString() == url)
                return errorContext = context;
            else
            {
                if (context.sourceFileMap && context.sourceFileMap[url])
                    return errorContext = context;
            }
        }
    );

    return errorContext; // we looked everywhere...
}

function checkForUncaughtException(context, object)
{
    if (object.flags & object.exceptionFlag)
    {
        if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe is exception\n");
        if (reUncaught.test(object.errorMessage))
        {
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("uncaught exception matches "+reUncaught+"\n");
            if (context.thrownStackTrace)
            {
                Firebug.errorStackTrace = context.thrownStackTrace;
                return true;
                if (FBTrace.DBG_ERRORS) FBTrace.dumpProperties("errors.observe trace.frames", context.thrownStackTrace.frames);
            }
            else
            {
                 if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe NO context.thrownStackTrace\n");
            }
        }
        else
        {
            if (FBTrace.DBG_ERRORS) FBTrace.sysout("errors.observe not an uncaught exception\n");
        }
    }
    return false;
}

function getExceptionContext(context)
{
    var errorWin = fbs.lastErrorWindow;  // not available unless Script panel is enabled.
    if (errorWin)
    {
        var errorContext = TabWatcher.getContextByWindow(errorWin);
        if (FBTrace.DBG_ERRORS)                                                                    /*@explore*/
            FBTrace.sysout("errors.observe exception context:"+errorContext+" errorWin"+errorWin+"\n");           /*@explore*/
        return errorContext;
    }
    return context;
}

function correctLineNumbersOnExceptions(context, object)
{
    var m = reException.exec(object.errorMessage);
    if (m)
    {
        var exception = m[1];
        if (exception)
            errorMessage = "uncaught exception: "+exception;
        var nsresult = m[2];
        if (nsresult)
            errorMessage += " ("+nsresult+")";
        sourceName = m[3];
        lineNumber = m[4];

        var correctedError = object.init(errorMessage, sourceName, object.sourceLine, lineNumber, object.columnNumber, object.flags, object.category);
    }
}

function correctLineNumbersWithStack(trace, object)
{
    if (FBTrace.DBG_ERRORS)                                                                            /*@explore*/
        FBTrace.dumpProperties("errors.observe showStackTrace trace frames:", trace.frames);                          /*@explore*/
    var stack_frame = trace.frames[0];
    if (stack_frame)
    {
        sourceName = stack_frame.href;
        lineNumber = stack_frame.lineNo;
    }
    var correctedError = object.init(object.errorMessage, sourceName, object.sourceLine,lineNumber, object.columnNumber, object.flags, object.category);
}

// ************************************************************************************************

Firebug.registerModule(Errors);

// ************************************************************************************************

}});
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var _PACKAGE_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/(.+)\/package-(summary|descr).html/;
var _CLASS_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/(.+).html/;
var _RESOURCE_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/android\/(R(?:\..+)?).html/;

var _GOOGLESOURCE_URL_TEMPLATE = '$BASEURL/$PROJECT/+/refs/heads/master/$TREE/$NAME_SLASH';
var _GOOGLESOURCE_RESOURCES_PATH = '$BASEURL/platform/frameworks/base/+/refs/heads/master/core/res/res/';
var _GOOGLESOURCE_SAMPLES_PATH = '$BASEURL/platform/development/+/master/samples';

var _RESOURCE_MAP = {
  'R'               : '',
  'R.anim'          : 'anim/',
  'R.animator'      : 'animator/',
  'R.array'         : 'values/arrays.xml',
  'R.attr'          : 'values/attrs.xml',
  'R.bool'          : 'values/bools.xml',
  'R.color'         : 'values/colors.xml',
  'R.dimen'         : 'values/dimens.xml',
  'R.drawable'      : ['drawable/', 'drawable-xhdpi/'],
  'R.id'            : 'values/ids.xml',
  'R.integer'       : 'integers.xml',
  'R.interpolator'  : 'interpolator/',
  'R.layout'        : 'layout/',
  'R.menu'          : 'menu/',
  'R.mipmap'        : ['mipmap-mdpi/', 'mipmap-xxhdpi/'],
  'R.plurals'       : 'values/strings.xml',
  'R.raw'           : 'raw/',
  'R.string'        : 'values/strings.xml',
  'R.style'         : ['values/styles.xml', 'values/themes.xml'],
  'R.styleable'     : 'values/attrs.xml',
  'R.xml'           : 'xml/'
};

var _PACKAGE_MAP = {
  'java'                         : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'javax'                        : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'org'                          : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'android'                      : { project:'platform/frameworks/base',     tree:'core/java' },
  'android.drm'                  : { project:'platform/frameworks/base',     tree:'drm/java' },
  'android.drm.mobile1'          : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.renderscript'         : { project:'platform/frameworks/base',     tree:'graphics/java' },
  'android.graphics'             : { project:'platform/frameworks/base',     tree:'graphics/java' },
  'android.icu     '             : { project:'platform/frameworks/base',     tree:'icu4j/java' },
  'android.security'             : { project:'platform/frameworks/base',     tree:'keystore/java' },
  'android.location'             : { project:'platform/frameworks/base',     tree:'location/java' },
  'android.media'                : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.mtp'                  : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.opengl'               : { project:'platform/frameworks/base',     tree:'opengl/java' },
  'android.sax'                  : { project:'platform/frameworks/base',     tree:'sax/java' },
  'android.telephony'            : { project:'platform/frameworks/base',     tree:'telephony/java' },
  'android.net.rtp'              : { project:'platform/frameworks/base',     tree:'voip/java' },
  'android.net.sip'              : { project:'platform/frameworks/base',     tree:'voip/java' },
  'android.net.wifi'             : { project:'platform/frameworks/base',     tree:'wifi/java' },
  'android.support.v4'           : { project:'platform/frameworks/support',  tree:'v4/java' },
  'android.support.v7'           : { project:'platform/frameworks/support',  tree:'v7/appcompat/src' },
  'android.support.v7.media'     : { project:'platform/frameworks/support',  tree:'v7/mediarouter/src' },
  'android.support.v7.graphics'  : { project:'platform/frameworks/support',  tree:'v7/palette/src' },
  'android.support.v13'          : { project:'platform/frameworks/support',  tree:'v13/java' },
  'android.support.v17.leanback' : { project:'platform/frameworks/support',  tree:'v17/leanback/src' }
};

var _TREE_REFINEMENTS = {
  'android.support.v7.app': [
    {
      regex: /MediaRoute/,
      tree: 'v7/mediarouter/src'
    }
  ],
  'android.support.v7.widget': [
    {
      regex: /RecyclerView|DefaultItemAnimator|OrientationHelper|LinearSmoothScroller/,
      tree: 'v7/recyclerview/src'
    },
    {
      regex: /(Linear|Grid|StaggeredGrid)LayoutManager/,
      tree: 'v7/recyclerview/src'
    },
    {
      regex: /CardView/,
      tree: 'v7/cardview/src'
    },
    {
      regex: /GridLayout|\.Space$/, // must appear after GridLayoutManager
      tree: 'v7/gridlayout/src'
    }
  ]
};

var _ESPRESSO_PACKAGE_PREFIX = 'android.support.test.espresso';

var _ESPRESSO_FOLDER_MAP = {
  'contrib' : 'contrib',
  'intent' : 'intents',
  'intent.matcher' : 'intents',
  'intent.rule' : 'intents'
}

function trimLastNamePart(s) {
  return s.replace(/\.[^.]*$/, '');
}

function getPackageInfo(packageName) {
  var tmpPackageName = packageName;
  while (tmpPackageName) {
    if (tmpPackageName in _PACKAGE_MAP) {
      var pi = {};
      pi.tree = _PACKAGE_MAP[tmpPackageName].tree;
      pi.project = _PACKAGE_MAP[tmpPackageName].project;
      return pi;
    }
    if (!tmpPackageName.match(/\./)) {
      break;
    }
    tmpPackageName = trimLastNamePart(tmpPackageName);
  }
  return null;
}

function getEspressoInfo(packageName) {
  if (packageName.indexOf(_ESPRESSO_PACKAGE_PREFIX) != 0) {
    return null;
  }
  var suffix = packageName.substring(_ESPRESSO_PACKAGE_PREFIX.length + 1);
  var folder = 'core'
  if (suffix in _ESPRESSO_FOLDER_MAP) {
    folder = _ESPRESSO_FOLDER_MAP[suffix]
  }
  return { suffix : suffix, folder : folder }
}

chrome.storage.local.get({
  baseUrl: 'https://android.googlesource.com'
}, function(items) {
  var url = window.location.href;
  var appendContent;

  var m;
  if (m = url.match(_PACKAGE_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    var packageName = nameSlash.replace(/\//g, '.');

    var pi = getPackageInfo(packageName);
    if (pi) {
      var url =
          _GOOGLESOURCE_URL_TEMPLATE
              .replace(/\$BASEURL/g, items.baseUrl)
              .replace(/\$PROJECT/g, pi.project)
              .replace(/\$TREE/g, pi.tree)
              .replace(/\$NAME_SLASH/g, nameSlash);

      var espressoInfo = getEspressoInfo(packageName);
      if (espressoInfo != null) {
         var suffix = espressoInfo.suffix.replace('.', '/')
         var folder = espressoInfo.folder
         url = url.replace('base/+/refs/heads/master/core/java/android/support/test/espresso/' + suffix,
                 'testing/+/android-support-test/espresso/');
         if (folder == 'core' || suffix.indexOf('/' != -1)) {
           url += folder + '/src/main/java/android/support/test/espresso/' + suffix;
         } else {
           url += folder;
         }
      }

      appendContent = [
          ' (view source listing)'
      ].join('');
    }

  } else if (m = url.match(_RESOURCE_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    if (nameSlash in _RESOURCE_MAP) {
      var destinations = _RESOURCE_MAP[nameSlash];
      if (!destinations.splice) {
        // Single string, convert to array
        destinations = [destinations];
      }
      appendContent = ' (';
      for (var i = 0; i < destinations.length; i++) {
        var resPath = destinations[i];
        appendContent += [
            (i == 0) ? '' : ' • ',
            '',
            (i == 0) ? 'view ' : '',
            'res/',
            resPath.replace(/\/$/,''),
            ''
        ].join('');
      }
      appendContent += ')';
    }

  } else if (m = url.match(_CLASS_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    var outerNameSlash = nameSlash.replace(/\..*$/, ''); // trim inner classes
    var outerNameDot = outerNameSlash.replace(/\//g, '.');
    var packageName = trimLastNamePart(outerNameDot);

    var pi = getPackageInfo(packageName);
    if (packageName in _TREE_REFINEMENTS) {
      var refinements = _TREE_REFINEMENTS[packageName];
      for (var i = 0; i < refinements.length; i++) {
        if (outerNameDot.match(refinements[i].regex)) {
          pi.tree = refinements[i].tree;
          break;
        }
      }
    }
    if (pi) {
      var url =
          _GOOGLESOURCE_URL_TEMPLATE
              .replace(/\$BASEURL/g, items.baseUrl)
              .replace(/\$PROJECT/g, pi.project)
              .replace(/\$TREE/g, pi.tree)
              .replace(/\$NAME_SLASH/g, outerNameSlash + '.java')

      var espressoInfo = getEspressoInfo(packageName);
      if (espressoInfo != null) {
         url = url.replace('base/+/refs/heads/master/core/java/android/support/test/espresso/',
             'testing/+/android-support-test/espresso/'
                 + espressoInfo.folder + '/src/main/java/android/support/test/espresso/');
      }

      appendContent = [
          ' (view source)'
      ].join('');
    }

  }

  if (appendContent) {
    var appendNode = document.createElement('span');
    appendNode.style.display = "inline-block";
    appendNode.innerHTML = appendContent;

    document
        .getElementById('jd-header')
        .getElementsByTagName('h1')[0]
        .appendChild(appendNode);
  }

  // rewrite any direct links to sample code
  var sampleLinks = document.querySelectorAll('a[href*="/resources/samples"]');
  for (var i = 0; i < sampleLinks.length; i++) {
    var link = sampleLinks[i];
    var codePath = link.href.split('resources/samples')[1];
    var rootSuffix = 'index.html'; // a rooted sample link
    var classSuffix = '.html'; // a specific class link, usually in ApiDemos
    if (codePath.indexOf(rootSuffix) > 0) {
      codePath = codePath.slice(0, codePath.indexOf(rootSuffix));
    } else if (classSuffix == codePath.slice(-classSuffix.length)) {
      codePath = codePath.slice(0, codePath.length - classSuffix.length) + '.java';
    }
    link.href = _GOOGLESOURCE_SAMPLES_PATH.replace(/\$BASEURL/g, items.baseUrl) + codePath;
  }

});
<commit_msg>Add missing support for new support libraries<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var _PACKAGE_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/(.+)\/package-(summary|descr).html/;
var _CLASS_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/(.+).html/;
var _RESOURCE_DOC_URL_REGEX = /http(?:s)?:\/\/d(?:eveloper)?.android.com\/reference\/android\/(R(?:\..+)?).html/;

var _GOOGLESOURCE_URL_TEMPLATE = '$BASEURL/$PROJECT/+/refs/heads/master/$TREE/$NAME_SLASH';
var _GOOGLESOURCE_RESOURCES_PATH = '$BASEURL/platform/frameworks/base/+/refs/heads/master/core/res/res/';
var _GOOGLESOURCE_SAMPLES_PATH = '$BASEURL/platform/development/+/master/samples';

var _RESOURCE_MAP = {
  'R'               : '',
  'R.anim'          : 'anim/',
  'R.animator'      : 'animator/',
  'R.array'         : 'values/arrays.xml',
  'R.attr'          : 'values/attrs.xml',
  'R.bool'          : 'values/bools.xml',
  'R.color'         : 'values/colors.xml',
  'R.dimen'         : 'values/dimens.xml',
  'R.drawable'      : ['drawable/', 'drawable-xhdpi/'],
  'R.id'            : 'values/ids.xml',
  'R.integer'       : 'integers.xml',
  'R.interpolator'  : 'interpolator/',
  'R.layout'        : 'layout/',
  'R.menu'          : 'menu/',
  'R.mipmap'        : ['mipmap-mdpi/', 'mipmap-xxhdpi/'],
  'R.plurals'       : 'values/strings.xml',
  'R.raw'           : 'raw/',
  'R.string'        : 'values/strings.xml',
  'R.style'         : ['values/styles.xml', 'values/themes.xml'],
  'R.styleable'     : 'values/attrs.xml',
  'R.xml'           : 'xml/'
};

var _PACKAGE_MAP = {
  'java'                                 : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'javax'                                : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'org'                                  : { project:'platform/libcore',             tree:'luni/src/main/java' },
  'android'                              : { project:'platform/frameworks/base',     tree:'core/java' },
  'android.drm'                          : { project:'platform/frameworks/base',     tree:'drm/java' },
  'android.drm.mobile1'                  : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.renderscript'                 : { project:'platform/frameworks/base',     tree:'graphics/java' },
  'android.graphics'                     : { project:'platform/frameworks/base',     tree:'graphics/java' },
  'android.icu'                          : { project:'platform/frameworks/base',     tree:'icu4j/java' },
  'android.security'                     : { project:'platform/frameworks/base',     tree:'keystore/java' },
  'android.location'                     : { project:'platform/frameworks/base',     tree:'location/java' },
  'android.media'                        : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.mtp'                          : { project:'platform/frameworks/base',     tree:'media/java' },
  'android.opengl'                       : { project:'platform/frameworks/base',     tree:'opengl/java' },
  'android.sax'                          : { project:'platform/frameworks/base',     tree:'sax/java' },
  'android.telephony'                    : { project:'platform/frameworks/base',     tree:'telephony/java' },
  'android.net.rtp'                      : { project:'platform/frameworks/base',     tree:'voip/java' },
  'android.net.sip'                      : { project:'platform/frameworks/base',     tree:'voip/java' },
  'android.net.wifi'                     : { project:'platform/frameworks/base',     tree:'wifi/java' },
  'android.support.v4'                   : { project:'platform/frameworks/support',  tree:'v4/java' },
  'android.support.v7'                   : { project:'platform/frameworks/support',  tree:'v7/appcompat/src' },
  'android.support.v7.media'             : { project:'platform/frameworks/support',  tree:'v7/mediarouter/src' },
  'android.support.v7.graphics'          : { project:'platform/frameworks/support',  tree:'v7/palette/src' },
  'android.support.v13'                  : { project:'platform/frameworks/support',  tree:'v13/java' },
  'android.support.v17.leanback'         : { project:'platform/frameworks/support',  tree:'v17/leanback/src' },
  'android.support.design'               : { project:'platform/frameworks/support',  tree:'design/src' },
  'android.support.customtabs'           : { project:'platform/frameworks/support',  tree:'customtabs/src' },
  'android.support.percent'              : { project:'platform/frameworks/support',  tree:'percent/src' },
  'android.support.app.recommendation'   : { project:'platform/frameworks/support',  tree:'recommendation/src' },
  'android.support.v7.preference'        : { project:'platform/frameworks/support',  tree:'v7/preference/src' },
  'android.support.v14.preference'       : { project:'platform/frameworks/support',  tree:'v14/preference/src' },
};

var _TREE_REFINEMENTS = {
  'android.support.v7.app': [
    {
      regex: /MediaRoute/,
      tree: 'v7/mediarouter/src'
    }
  ],
  'android.support.v7.widget': [
    {
      regex: /RecyclerView|DefaultItemAnimator|OrientationHelper|LinearSmoothScroller/,
      tree: 'v7/recyclerview/src'
    },
    {
      regex: /(Linear|Grid|StaggeredGrid)LayoutManager/,
      tree: 'v7/recyclerview/src'
    },
    {
      regex: /CardView/,
      tree: 'v7/cardview/src'
    },
    {
      regex: /GridLayout|\.Space$/, // must appear after GridLayoutManager
      tree: 'v7/gridlayout/src'
    }
  ]
};

var _ESPRESSO_PACKAGE_PREFIX = 'android.support.test.espresso';

var _ESPRESSO_FOLDER_MAP = {
  'contrib' : 'contrib',
  'intent' : 'intents',
  'intent.matcher' : 'intents',
  'intent.rule' : 'intents'
}

function trimLastNamePart(s) {
  return s.replace(/\.[^.]*$/, '');
}

function getPackageInfo(packageName) {
  var tmpPackageName = packageName;
  while (tmpPackageName) {
    if (tmpPackageName in _PACKAGE_MAP) {
      var pi = {};
      pi.tree = _PACKAGE_MAP[tmpPackageName].tree;
      pi.project = _PACKAGE_MAP[tmpPackageName].project;
      return pi;
    }
    if (!tmpPackageName.match(/\./)) {
      break;
    }
    tmpPackageName = trimLastNamePart(tmpPackageName);
  }
  return null;
}

function getEspressoInfo(packageName) {
  if (packageName.indexOf(_ESPRESSO_PACKAGE_PREFIX) != 0) {
    return null;
  }
  var suffix = packageName.substring(_ESPRESSO_PACKAGE_PREFIX.length + 1);
  var folder = 'core'
  if (suffix in _ESPRESSO_FOLDER_MAP) {
    folder = _ESPRESSO_FOLDER_MAP[suffix]
  }
  return { suffix : suffix, folder : folder }
}

chrome.storage.local.get({
  baseUrl: 'https://android.googlesource.com'
}, function(items) {
  var url = window.location.href;
  var appendContent;

  var m;
  if (m = url.match(_PACKAGE_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    var packageName = nameSlash.replace(/\//g, '.');

    var pi = getPackageInfo(packageName);
    if (pi) {
      var url =
          _GOOGLESOURCE_URL_TEMPLATE
              .replace(/\$BASEURL/g, items.baseUrl)
              .replace(/\$PROJECT/g, pi.project)
              .replace(/\$TREE/g, pi.tree)
              .replace(/\$NAME_SLASH/g, nameSlash);

      var espressoInfo = getEspressoInfo(packageName);
      if (espressoInfo != null) {
         var suffix = espressoInfo.suffix.replace('.', '/')
         var folder = espressoInfo.folder
         url = url.replace('base/+/refs/heads/master/core/java/android/support/test/espresso/' + suffix,
                 'testing/+/android-support-test/espresso/');
         if (folder == 'core' || suffix.indexOf('/' != -1)) {
           url += folder + '/src/main/java/android/support/test/espresso/' + suffix;
         } else {
           url += folder;
         }
      }

      appendContent = [
          ' (view source listing)'
      ].join('');
    }

  } else if (m = url.match(_RESOURCE_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    if (nameSlash in _RESOURCE_MAP) {
      var destinations = _RESOURCE_MAP[nameSlash];
      if (!destinations.splice) {
        // Single string, convert to array
        destinations = [destinations];
      }
      appendContent = ' (';
      for (var i = 0; i < destinations.length; i++) {
        var resPath = destinations[i];
        appendContent += [
            (i == 0) ? '' : ' • ',
            '',
            (i == 0) ? 'view ' : '',
            'res/',
            resPath.replace(/\/$/,''),
            ''
        ].join('');
      }
      appendContent += ')';
    }

  } else if (m = url.match(_CLASS_DOC_URL_REGEX)) {
    var nameSlash = m[1];
    var outerNameSlash = nameSlash.replace(/\..*$/, ''); // trim inner classes
    var outerNameDot = outerNameSlash.replace(/\//g, '.');
    var packageName = trimLastNamePart(outerNameDot);

    var pi = getPackageInfo(packageName);
    if (packageName in _TREE_REFINEMENTS) {
      var refinements = _TREE_REFINEMENTS[packageName];
      for (var i = 0; i < refinements.length; i++) {
        if (outerNameDot.match(refinements[i].regex)) {
          pi.tree = refinements[i].tree;
          break;
        }
      }
    }
    if (pi) {
      var url =
          _GOOGLESOURCE_URL_TEMPLATE
              .replace(/\$BASEURL/g, items.baseUrl)
              .replace(/\$PROJECT/g, pi.project)
              .replace(/\$TREE/g, pi.tree)
              .replace(/\$NAME_SLASH/g, outerNameSlash + '.java')

      var espressoInfo = getEspressoInfo(packageName);
      if (espressoInfo != null) {
         url = url.replace('base/+/refs/heads/master/core/java/android/support/test/espresso/',
             'testing/+/android-support-test/espresso/'
                 + espressoInfo.folder + '/src/main/java/android/support/test/espresso/');
      }

      appendContent = [
          ' (view source)'
      ].join('');
    }

  }

  if (appendContent) {
    var appendNode = document.createElement('span');
    appendNode.style.display = "inline-block";
    appendNode.innerHTML = appendContent;

    document
        .getElementById('jd-header')
        .getElementsByTagName('h1')[0]
        .appendChild(appendNode);
  }

  // rewrite any direct links to sample code
  var sampleLinks = document.querySelectorAll('a[href*="/resources/samples"]');
  for (var i = 0; i < sampleLinks.length; i++) {
    var link = sampleLinks[i];
    var codePath = link.href.split('resources/samples')[1];
    var rootSuffix = 'index.html'; // a rooted sample link
    var classSuffix = '.html'; // a specific class link, usually in ApiDemos
    if (codePath.indexOf(rootSuffix) > 0) {
      codePath = codePath.slice(0, codePath.indexOf(rootSuffix));
    } else if (classSuffix == codePath.slice(-classSuffix.length)) {
      codePath = codePath.slice(0, codePath.length - classSuffix.length) + '.java';
    }
    link.href = _GOOGLESOURCE_SAMPLES_PATH.replace(/\$BASEURL/g, items.baseUrl) + codePath;
  }

});
<|endoftext|>


<commit_before>var esprima = require('esprima'),
	traverse = require('./traverse'),
	escodegen = require('escodegen'),
	comparify = require('comparify'),
	optionsNormalize = require('./options_normalize');

module.exports = function(load, options){
	var source = load.source;

	// If we need to normalize then we must use esprima.
	if(options.normalizeMap || options.normalize) {
		var output = esprima.parse(source.toString());

		traverse(output, function(obj){
			if(comparify(obj, {
				"type": "CallExpression",
				"callee": {
					"type": "Identifier",
					"name": "require"
				}
			})) {
				var arg = obj.arguments[0];
				if(arg.type === "Literal") {
					var val = arg.value;
					arg.value = optionsNormalize(options, val, load.name, load.address);
					arg.raw = '"'+arg.value+'"';
				}

				return false;
			}
		});

		source = escodegen.generate(output);
	}

	return "define('"+load.name+"', function(require, exports, module) {\n"
		+source+
		"\n});";

};
<commit_msg>FIX: check have options<commit_after>var esprima = require('esprima'),
	traverse = require('./traverse'),
	escodegen = require('escodegen'),
	comparify = require('comparify'),
	optionsNormalize = require('./options_normalize');

module.exports = function(load, options){
	var source = load.source;

	// If we need to normalize then we must use esprima.
	if(options && (options.normalizeMap || options.normalize)) {
		var output = esprima.parse(source.toString());

		traverse(output, function(obj){
			if(comparify(obj, {
				"type": "CallExpression",
				"callee": {
					"type": "Identifier",
					"name": "require"
				}
			})) {
				var arg = obj.arguments[0];
				if(arg.type === "Literal") {
					var val = arg.value;
					arg.value = optionsNormalize(options, val, load.name, load.address);
					arg.raw = '"'+arg.value+'"';
				}

				return false;
			}
		});

		source = escodegen.generate(output);
	}

	return "define('"+load.name+"', function(require, exports, module) {\n"
		+source+
		"\n});";

};
<|endoftext|>